package avicit.im.lantop.userauthset.action;

import avicit.cbb.appreg.service.CommSysInfoIntfsService;
import avicit.cbb.businessclass.system.dataauth.domain.CbbAuthResource;
import avicit.cbb.businessclass.system.dataauth.service.BaseExtendAuthService;
import avicit.cbb.businessclass.system.dataauth.service.api.BaseExtendAuthServiceApi;
import avicit.cbb.elefileupdown.service.FileUploadIntfsService;
import avicit.cbb.elefileupdown.service.api.FileUploadIntfsServiceApi;
import avicit.cbb.search.solr.service.LantopSolrTimeTaskService;
import avicit.cbb.searcheng.service.CbbSearchengIntfsService;
import avicit.cbb.tabledefine.service.CommTableManagerIntfsService;
import avicit.cbb.tabledefine.service.api.CommTableManagerIntfsServiceApi;
import avicit.cbb.techclass.elefileupdown.service.JProperties;
import avicit.im.lantop.archiveclassmanager.service.ArchiveClassManagerIntfsService;
import avicit.im.lantop.archiveclassmanager.service.api.ArchiveClassManagerIntfsServiceApi;
import avicit.im.lantop.userauthset.domain.*;
import avicit.im.lantop.userauthset.service.UserAuthIntfsService;
import avicit.im.lantop.userauthset.service.UserAuthService;
import avicit.im.lantop.userauthset.service.api.UserAuthIntfsServiceApi;
import avicit.im.lantop.userauthset.service.api.UserAuthServiceApi;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.api.syslookup.SysLookupAPI;
import avicit.platform6.api.syslookup.dto.SysLookupSimpleVo;
import avicit.platform6.api.syslookup.impl.SysLookupAPImpl;
import avicit.platform6.api.sysuser.SysUserAPI;
import avicit.platform6.api.sysuser.impl.SysUserAPImpl;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.JsonHelper;
import avicit.platform6.commons.utils.JsonUtils;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.jdbc.Page;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.spring.SpringFactory;
import avicit.platform6.modules.system.sysfileupload.domain.SysFileUpload;
import avicit.platform6.modules.system.sysfileupload.service.SysFileUploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>金航数码科技有限责任公司</p>
 * <p>作者：张坚</p>
 * <p>邮箱：18629436468@163.com</p>
 * <p>创建时间： 2014-11-24 下午2:02:52 </p>
 * <p>类说明：用户权限设置Controller类
 * <p>修改记录： </p>
 */
@Controller
@SuppressWarnings({"unchecked", "deprecation"})
@RequestMapping("/UserAuthSetController")
public class UserAuthSetController {

	private static Map<String, BaseExtendAuthService> servers;
	private String sysId;

	@Autowired(required = true)
	private UserAuthServiceApi userAuthService;
	
	@Autowired(required = true)
	private LantopSolrTimeTaskService solrService;

	@Autowired(required = true)
	private CommSysInfoIntfsService commSysInfoIntfsService;

	@Resource(name = "BaseAuthService")
	private BaseExtendAuthServiceApi baseExtendAuthService; // CBB项目服务实现类

	@Resource(name = "ArchiveServiceUserSetBaseAuthServiceImpl")
	private BaseExtendAuthServiceApi archiveServiceUserSetBaseAuthService; // 档案用户数据权限设置服务

	@Autowired
	private CommTableManagerIntfsServiceApi commTableManagerIntfsService;

	@Autowired
	private UserAuthIntfsServiceApi userAuthIntfsService;    //20160615
	
	@Autowired
	private ArchiveClassManagerIntfsServiceApi archiveClassManagerIntfsService;
	
	@Autowired
	private CbbSearchengIntfsService cbbSearchengIntfsService;    //20160615

	SysUserAPI sysUserLoaderI = SpringFactory.getBean(SysUserAPImpl.class);
	SysLookupAPI sysLookupLoaderI = SpringFactory.getBean(SysLookupAPImpl.class);
	
	@Autowired
	private SysFileUploadService sfuService;
	
	@Autowired
	private FileUploadIntfsServiceApi fileUploadIntfsService;
	
	// Collection<SysLookupSimpleVo> authTypeList = sysLookupLoaderI.getLookUpListByType("LANTOP_AUTH_TYPE"); //权限类型
	// Collection<SysLookupSimpleVo> operCharacterList = sysLookupLoaderI.getLookUpListByType("CBB_OPER_CHARACTER"); //运算符
	// Collection<SysLookupSimpleVo> logicOperList = sysLookupLoaderI.getLookUpListByType("CBB_LOGIC_OPER"); //逻辑关系

	public UserAuthSetController() {
		checkServerCache();
	}

	/**
	 * 加载服务
	 * @author 张坚  void
	 */
	private void checkServerCache() {
		if (servers == null) {
			servers = SpringFactory.getApplicationContext().getBeansOfType(BaseExtendAuthService.class); // 加载所有实现了BaseExtendAuthService接口的服务类
		}
	}

	/**
	 * 写入sysId
	 * @author 张坚 
	 * @param request
	 * @throws Exception void
	 */
	@RequestMapping("setSysId")
	public void setSysId(HttpServletRequest request) throws Exception {
		// 获取系统标识ID
		this.sysId = request.getParameter("sysId");
		this.sysId = "LANTOP"; // 系统ID
	}

	/**
	 * 获取所有服务信息
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/getAuthService")
	@ResponseBody
	public Map<String,Object> getAuthService(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		// 获取系统标识ID
		this.sysId = request.getParameter("sysId");
		this.sysId = "LANTOP"; // 系统ID

		String serviceName = request.getParameter("serviceName");// 查询条件

		List<HashMap<String, String>> serviceList = new ArrayList<HashMap<String, String>>();
		Iterator<String> itr = servers.keySet().iterator();
		while (itr.hasNext()) {
			String key = itr.next();
			BaseExtendAuthService server = servers.get(key);
			if (serviceName != null && server.getServiceTitle().indexOf(serviceName) == -1) {
				continue;
			}
			HashMap<String, String> result = new HashMap<String, String>();
			result.put("SERVICE_ID", server.getServiceId());
			result.put("SERVICE_NAME", server.getServiceTitle());
			serviceList.add(result);
		}
		map.put("rows", serviceList);
		map.put("total", servers.size());
		return map;
	}

	/**
	 * 加载菜单
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/getMenu")
	@ResponseBody
	public Map<String,Object> getMenu(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String operateClassId = request.getParameter("operateClassId");
		String id = request.getParameter("id");
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		try {
			if (StringUtils.isEmpty(id)) {
				id = "-1";
			}
			nodes = this.userAuthService.getMenuTreeNode(SessionHelper.getCurrentOrgIdentity(),ThreadContextHelper.getOrgId(), this.sysId, id, operateClassId);
			map.put("result", OpResult.success.ordinal());
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", OpResult.failure.ordinal());
			map.put("msg", "后台处理异常, " + e.getMessage());
		}
		map.put("data", nodes);
		return map;
	}

	/**
	 * 跳转权限设置页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toAuthConfigJsp")
	public ModelAndView toAuthConfigJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		String serviceId = request.getParameter("serviceId");
		if (serviceId.equals("LANTOP_AUTH_SERVER_FUNC")) {
			mav.setViewName("avicit/im/lantop/userauthset/IframeArchiveFunctionAuthSet");
		} else if (serviceId.equals("LANTOP_AUTH_SERVER_USERSET")) {
			mav.setViewName("avicit/im/lantop/userauthset/IframeArchiveServiceUserSet");
			Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
			List<Map<String, String>> userAuthColList = new ArrayList<Map<String, String>>();
			int userAuthColSize = operateInfoMap.keySet().size();
			for (int i = 1; i <= userAuthColSize; i++) {
				if (i > 9) {
					// 这种写法目前最多支持9中权限，如果要支持更多权限，jsp页面中的脚本方法同时也需要修改
					break;
				}
				Map<String, String> map = new HashMap<String, String>();
				String key = "A" + i;// 通用代码以字母A开头，按顺序1、2.。。排列，这种写法目前最多支持9中权限，如果要支持更多权限，jsp页面中的脚本方法同时也需要修改
				map.put("code", key);
				map.put("name", operateInfoMap.get(key));
				userAuthColList.add(map);
			}
			mav.addObject("userAuthColList", userAuthColList);
			mav.addObject("authCount", userAuthColList.size());
		}
		return mav;
	}

	/**
	 * 加载模块下资源
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/getResource")
	@ResponseBody
	public Map<String,Object> getResource(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String targetId = request.getParameter("targetId"); // 授权维度ID
		String menuId = request.getParameter("menuId");

		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("targetId", targetId);
		parameter.put("menuId", menuId);
		parameter.put("orgId", ThreadContextHelper.getOrgId());
		parameter.put("sysId", this.sysId);
		List<Map<String, Object>> list = this.userAuthService.getResource(parameter);
		map.put("rows", list);
		map.put("total", list.size());
		return map;
	}

	/**
	 * 保存档案功能操作权限设置
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/saveResourceAuth")
	@ResponseBody
	public Map<String,Object> saveResourceAuth(HttpServletRequest request) throws Exception {
		Map<String,Object> maps = new HashMap<>();

		String targetType = request.getParameter("targetType"); // 授权维度类型
		String targetId = request.getParameter("targetId"); // 授权维度ID
		String code = request.getParameter("menuId"); // 所选菜单ID
		String name = request.getParameter("menuName"); // 所选菜单名称
		String datas = request.getParameter("datas"); // 资源列表
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("orgId", ThreadContextHelper.getOrgId());
		parameter.put("sysId", this.sysId);
		parameter.put("targetId", targetId);
		parameter.put("serviceId", "LANTOP_AUTH_SERVER_FUNC");
		parameter.put("menuId", code);

		List<CbbAuthResource> cbbAuthResources = new ArrayList<CbbAuthResource>();
		Map<String, Object>[] resourceDatas = JsonUtils.newInstance().Json2Bean2DataGrid(datas, HashMap[].class);
		for (int i = 0; i < resourceDatas.length; i++) {
			Map<String, Object> map = resourceDatas[i];
			CbbAuthResource cbbAuthResource = new CbbAuthResource();
			cbbAuthResource.setOrgId(ThreadContextHelper.getOrgId()); // 组织ID
			cbbAuthResource.setDeptId(ThreadContextHelper.getDeptId()); // 部门ID
			cbbAuthResource.setSysId(this.sysId); // 系统标识ID
			// cbbAuthResource.setId((String)map.get("ID"));
			cbbAuthResource.setTargetType(targetType); // 授权维度类型
			cbbAuthResource.setTargetId(targetId); // 授权维度ID
			cbbAuthResource.setAuthServiceId("LANTOP_AUTH_SERVER_FUNC");
			cbbAuthResource.setCode(code); // 所选菜单ID
			cbbAuthResource.setName(name); // 所选菜单名称
			cbbAuthResource.setActionType((String) map.get("FUNC_OPERATION_CODE")); // 操作类型：资源编号
			cbbAuthResource.setOperateAuth(null == map.get("OPERATE_AUTH") ? "0" : map.get("OPERATE_AUTH") + ""); // 允许：是1，否0
			cbbAuthResources.add(cbbAuthResource);
		}
		try {
			this.userAuthService.saveFuncResourceConfig(cbbAuthResources, parameter);
			maps.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			maps.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}

		return maps;
	}

	/**
	 * 获取维度下所有用户
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/getAuthUser")
	@ResponseBody
	public Map<String,Object> getAuthUser(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String targetType = request.getParameter("targetType"); // 授权目标类型
		String targetId = request.getParameter("targetId"); // 授权目标ID
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		String targetName = request.getParameter("targetName");
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));
		
		String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);

		if ("1".equals(targetType)) {
			//this.userAuthService.getGroupUser(page, targetId); // 群组
			this.userAuthService.getRoleUser(page, targetName,orgIdentity);
		} else if ("2".equals(targetType)) {
			this.userAuthService.getDetpUser(page, targetId,orgIdentity); // 部门
		} else if ("3".equals(targetType)) {
			this.userAuthService.getUser(page, targetId,orgIdentity); // 用户
		} else if ("4".equals(targetType)) {
			this.userAuthService.getPositionUser(page, targetId,orgIdentity); // 岗位
		}

		map.put("rows", page.getEntities());
		map.put("total", page.getEntityCount());

		return map;
	}

	/**
	 * 加载档案分类树，用户权限设置信息
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/getArchiveClass")
	@ResponseBody
	public Map<String,Object> getArchiveClass(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		String targetId = request.getParameter("targetId");
		if (null == targetId || targetId.equals("")) {
			// targetId为空表示没有选中用户，用户权限设置treegrid则为空
			map.put("rows", "");
		} else {
			Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
			int userAuthColSize = operateInfoMap.keySet().size();
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("targetType", targetType);
			param.put("targetId", targetId);
			param.put("orgId", ThreadContextHelper.getOrgId());
			param.put("sysId", this.sysId);
			param.put("userAuthColSize", userAuthColSize);
			List<Map<String, Object>> list = this.userAuthService.getArchiveClass(param);
			this.createTreegridNode(list);
			map.put("rows", list);
		}
		return map;
	}

	/**
	 * 构建treegrid节点对象
	 * @author 张坚 
	 * @param list
	 * @throws Exception void
	 */
	public void createTreegridNode(List<Map<String, Object>> list) throws Exception {
		Map<String, Object> map = null;
		for (int i = 0; i < list.size(); i++) {
			map = list.get(i);
			String nodeId = (String) map.get("PARENT_ID");
			String archiveType = (String) map.get("ARCHIVE_TYPE");
			String nodeType = (String) map.get("ARCHIVE_CLASS_NODE_TYPE");
			if ("ROOT".equals(((String) map.get("PARENT_ID")))) {
				map.put("_parentId", null);
			} else {
				map.put("_parentId", map.get("PARENT_ID"));
			}
			if (null != archiveType && !"0".equals(archiveType) || "1".equals(nodeType) || "2".equals(nodeType)) {
				map.put("state", "closed");
			} else {
				map.put("state", "open");
			}
			

			if ("ROOT".equals(nodeId)) { // 根节点
				map.put("iconCls", "icon-im-newnorg");
			} else if (null != archiveType && "-1".equals(archiveType) && null == nodeType) { // 档案类型 -1 物理表
				map.put("iconCls", "icon-im-newntable");
			} else if (null != archiveType && "0".equals(archiveType) && null == nodeType) { // 0 模版文件夹
				map.put("iconCls", "icon-im-newnmodulefile");
			} else if (null != archiveType && "1".equals(archiveType) && null == nodeType) { // 1 标识文件
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != archiveType && "2".equals(archiveType) && null == nodeType) { // 2 档案
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != archiveType && "3".equals(archiveType) && null == nodeType) { // 3 专题库
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != archiveType && "4".equals(archiveType) && null == nodeType) { // 4 多媒体
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != archiveType && "5".equals(archiveType) && null == nodeType) { // 5 项目归档计划
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != archiveType && "6".equals(archiveType) && null == nodeType) { // 6 管务
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != archiveType && "7".equals(archiveType) && null == nodeType) { // 7 其他
				map.put("iconCls", "icon-im-newnmodulelib");
			}  else if (null != archiveType && "8".equals(archiveType) && null == nodeType) { // 8 资料
				map.put("iconCls", "icon-im-newnmodulelib");
			}  else if (null != archiveType && "9".equals(archiveType) && null == nodeType) { // 9 图书
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != archiveType && "10".equals(archiveType) && null == nodeType) { // 10 虚拟表
				map.put("iconCls", "icon-im-newnmodulelib");
			}  else if (null != archiveType && "TECH".equals(archiveType) && null == nodeType) { // TECH 产品类
				map.put("iconCls", "icon-im-newnmodulelib");
			} else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
				map.put("iconCls", "icon-im-newnmodulefile");
			} else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
				map.put("iconCls", "icon-im-newndatanode");
			}
		}
	}

	/**
	 * 保存用户数据权限设置
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/saveUserSetDataAuth")
	@ResponseBody
	public Map<String,Object> saveUserSetDataAuth(HttpServletRequest request) throws Exception {
		Map<String,Object> maps = new HashMap<>();
		//获取有变化的节点(20160711 add)
		String nodeIdCheck = request.getParameter("nodeIdCheck");     //条目浏览
		String nodeIdQwCheck = request.getParameter("nodeIdQwCheck");   //全文浏览
		//nodeIds去重复数据
		String nodeIdsSolr = "";
		if (!"".equals(nodeIdCheck)) {
			String[] nodeIds = nodeIdCheck.split(",");
			List<String> list = new ArrayList<String>();
			for (int i = 0; i < nodeIds.length; i++) {
				if (!list.contains(nodeIds[i])) {
					if ("2".equals(this.userAuthService.getClassNodeType(nodeIds[i]))) {
						list.add(nodeIds[i]);
					}
				}
			}
			Object list2[] = list.toArray();
			for (int i = 0; i < list2.length; i++) {
				if (i == (list2.length - 1)) {
					nodeIdsSolr += list2[i] + "";
				} else {
					nodeIdsSolr += list2[i] + ",";
				}
			}
		}
		// 全文浏览
		String nodeIdsQwSolr = "";
		if (!"".equals(nodeIdQwCheck)) {
			String[] nodeIds = nodeIdQwCheck.split(",");
			List<String> list = new ArrayList<String>();
			for (int i = 0; i < nodeIds.length; i++) {
				if (!list.contains(nodeIds[i])) {
					if ("2".equals(this.userAuthService.getClassNodeType(nodeIds[i]))) {
						list.add(nodeIds[i]);
					}
				}
			}
			Object list2[] = list.toArray();
			for (int i = 0; i < list2.length; i++) {
				if (i == (list2.length - 1)) {
					nodeIdsQwSolr += list2[i] + "";
				} else {
					nodeIdsQwSolr += list2[i] + ",";
				}
			 }
		 }
		 
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String targetId = request.getParameter("targetId"); // 授权维度ID：用户ID;群组授时这里的targetId是群组ID
		String datas = request.getParameter("datas"); // 资源列表
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("orgId", ThreadContextHelper.getOrgId());
		parameter.put("sysId", this.sysId);
		parameter.put("targetId", targetId);
		parameter.put("serviceId", "LANTOP_AUTH_SERVER_USERSET");
		// 用户数据权限配置
		Map<String, Object>[] userSetDatas = JsonUtils.newInstance().Json2Bean2DataGrid(datas, HashMap[].class);
		// 要保存的权限集合
		List<CbbAuthResource> cbbAuthResources = new ArrayList<CbbAuthResource>();
		// 要删除的权限字符串，逗号分隔
		StringBuffer delCbbAuthResourcesIds = new StringBuffer();
		Map<String, Object> map = null;
		// 已经注册的数据权限类型
		Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
		for (int i = 0; i < userSetDatas.length; i++) {
			map = userSetDatas[i];
			// 只操作数据节点
			// if(null != map.get("ARCHIVE_CLASS_NODE_TYPE") && map.get("ARCHIVE_CLASS_NODE_TYPE").toString().equals("2")){
			// if(null != map.get("ARCHIVE_CLASS_NODE_TYPE")){
			StringBuffer operateTypeCodes = new StringBuffer(); // 权限类型CODE串
			StringBuffer operateTypeNames = new StringBuffer(); // 权限类型NAME串
			// 遍历已注册的数据权限类型值
			int userAuthColSize = operateInfoMap.keySet().size();
			for (int j = 1; j <= userAuthColSize; j++) {
				String key = "A" + j;// 通用代码以字母A开头
				String operateType = (String) map.get(key); // 权限类型值
				operateType = operateType.replace(key, ""); // 动态列区分需要每个列的默认值为自己本身的列名，这里获取到值后要清空标识的列名
				operateTypeCodes.append(key);
				operateTypeNames.append(operateType);
				// 最后一次不拼接逗号
				if (j != userAuthColSize) {
					operateTypeCodes.append(","); // 英文逗号
					operateTypeNames.append(","); // 英文逗号
				}
			}
			// 0,0,0,0标识没有选中的记录，只保存有授权的记录
			// if(!operateTypeNames.toString().equals("0,0,0,0")){

			// 根据targetType,targetId,authServiceId,res_code like 'code_%',dataAuth is not null判断是否存在条件信息
			int qualification = this.userAuthService.getLantopUserAuthSetExtendCount(targetType, targetId, "LANTOP_AUTH_SERVER_USERSET", (String) map.get("ID"));
			// 只有存在授权的记录保存并且已存在sql条件设置
			if (operateTypeNames.indexOf("1") >= 0 || qualification > 0) {
				String code = (String) map.get("ID"); // 档案分类树节点ID
				String name = (String) map.get("ARCHIVE_CLASS_NODE_NAME"); // 档案分类树节点名称
				String cbbAuthResourceId = (String) map.get("CBB_AUTH_RESOURCE_ID"); // 权限资源信息ID

				CbbAuthResource cbbAuthResource = new CbbAuthResource();
				cbbAuthResource.setId(cbbAuthResourceId);
				cbbAuthResource.setOrgId(ThreadContextHelper.getOrgId()); // 组织ID
				cbbAuthResource.setDeptId(ThreadContextHelper.getDeptId()); // 部门ID
				cbbAuthResource.setSysId(this.sysId); // 系统标识ID
				cbbAuthResource.setTargetType(targetType); // 授权维度类型
				cbbAuthResource.setTargetId(targetId); // 授权维度ID
				cbbAuthResource.setAuthServiceId("LANTOP_AUTH_SERVER_USERSET");
				cbbAuthResource.setCode(code); // 所选菜单ID
				cbbAuthResource.setName(name); // 所选菜单名称
				cbbAuthResource.setActionType(operateTypeCodes.toString()); // 授权类型CODE字符串
				cbbAuthResource.setOperateAuth(operateTypeNames.toString()); // 授权类型NAME字符串
				cbbAuthResources.add(cbbAuthResource);
			} else {
				// 2014年12月15日修改：之前已经存在授权，此次操作所有权限被取消，则要删除CBB_AUTH_RESOURCE表授权记录，同时删除LANTOP_USER_AUTH_SET_EXTEND表操作权限设置信息
				// 之前使用的先删除所有授权信息，在保存此次所有授权信息方法会导致已经设置过操作权限LANTOP_USER_AUTH_SET_EXTEND表的记录操作权限和授权表CBB_AUTH_RESOURCE记录脱离关系，导致所有关系丢失
				// 删除被取消授权或未被授权的记录，同时删除操作权限设置
				String cbbAuthResourceId = (String) map.get("CBB_AUTH_RESOURCE_ID"); // 权限资源信息ID
				if (null != cbbAuthResourceId && !cbbAuthResourceId.equals("")) {
					// 存在授权信息，此次操作取消了所有授权信息
					delCbbAuthResourcesIds.append(cbbAuthResourceId);
					delCbbAuthResourcesIds.append(",");
				}
			}
		}
		// }
		try {
			if (null != delCbbAuthResourcesIds && !"".equals(delCbbAuthResourcesIds.toString())) {
				parameter.put("delCbbAuthResourcesIds", delCbbAuthResourcesIds.substring(0, delCbbAuthResourcesIds.length() - 1).toString()); // 要删除的权限资源信息ID串
			}
			this.userAuthService.saveResourceConfig(cbbAuthResources, parameter);

			Map<String,Object> nodesMap = new HashMap<String,Object>();
			if (!"".equals(nodeIdsSolr)) {
				nodesMap.put("tmNodes", nodeIdsSolr);
			}
			if (!"".equals(nodeIdsQwSolr)) {
				nodesMap.put("qwNodes", nodeIdsQwSolr);
			}
			if (!"".equals(nodeIdsSolr) || !"".equals(nodeIdsQwSolr)) {
				nodesMap.put("flag", "2");
				nodesMap.put("orgId", ThreadContextHelper.getOrgId());
				nodesMap.put("deptId", ThreadContextHelper.getDeptId());
				nodesMap.put("sysId", sysId);
				solrService.insertSolrInfos(nodesMap);
				//this.updateSolrIndexTools(request,nodesMap);
			}
			maps.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			maps.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}
		return maps;
	}
	
	/**
	 * 保存用户数据权限设置
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/saveUserSetDataAuthBySelect")
	@ResponseBody
	public Map<String,Object> saveUserSetDataAuthBySelect(HttpServletRequest request) throws Exception {
		Map<String,Object> maps = new HashMap<>();
		String orgId = ThreadContextHelper.getOrgId();
		String deptId = ThreadContextHelper.getDeptId();
		String targetType = request.getParameter("targetType");// 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		//targetType = "3";
		String targetId = request.getParameter("targetId"); // 授权维度ID：用户ID;群组授时这里的targetId是群组ID
		String targetNodeId = request.getParameter("targetNodeId");
		String authString = request.getParameter("authString");
		//String[] authStringArray = authString.split(",");
		List<Map<String, Object>> lacList = this.archiveClassManagerIntfsService.getSelectNodeChild(orgId, deptId, this.sysId, targetNodeId);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("nodeId", targetNodeId);
		param.put("targetId", targetId);
		param.put("targetType", targetType);
		List<Map<String, Object>> authList = this.userAuthService.getUserAuthDatasByParam(param);
		// nodeIds去重复数据
		String nodeIdsSolr = "";
		List<String> listtm = new ArrayList<String>();
		for (int i = 0; i < lacList.size(); i++) {
			Map<String, Object> lacMap = lacList.get(i);
			if (!listtm.contains(lacMap.get("ID"))) {
				if ("2".equals(this.userAuthService.getClassNodeType(lacMap.get("ID").toString()))) {
					listtm.add(lacMap.get("ID").toString());
				}
			}
		}
		Object list2tm[] = listtm.toArray();
		for (int i = 0; i < list2tm.length; i++) {
			if (i == (list2tm.length - 1)) {
				nodeIdsSolr += list2tm[i] + "";
			} else {
				nodeIdsSolr += list2tm[i] + ",";
			}
		}
		// 全文浏览
		String nodeIdsQwSolr = "";
		List<String> listqw = new ArrayList<String>();
		for (int i = 0; i < lacList.size(); i++) {
			Map<String, Object> lacMap = lacList.get(i);
			if (!listqw.contains(lacMap.get("ID"))) {
				if ("2".equals(this.userAuthService.getClassNodeType(lacMap.get("ID").toString()))) {
					listqw.add(lacMap.get("ID").toString());
				}
			}
		}
		Object list2qw[] = listqw.toArray();
		for (int i = 0; i < list2qw.length; i++) {
			if (i == (list2qw.length - 1)) {
				nodeIdsQwSolr += list2qw[i] + "";
			} else {
				nodeIdsQwSolr += list2qw[i] + ",";
			}
		}
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("orgId", orgId);
		parameter.put("sysId", this.sysId);
		parameter.put("targetId", targetId);
		parameter.put("serviceId", "LANTOP_AUTH_SERVER_USERSET");
		// 要保存的权限集合
		List<CbbAuthResource> cbbAuthResources = new ArrayList<CbbAuthResource>();
		// 要删除的权限字符串，逗号分隔
		StringBuffer delCbbAuthResourcesIds = new StringBuffer();
		Map<String, Object> map = null;
		// 已经注册的数据权限类型
		Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
		for (int i = 0; i < lacList.size(); i++) {
			map = lacList.get(i);
			String classId = (String) map.get("ID");
			// 只操作数据节点
			// if(null != map.get("ARCHIVE_CLASS_NODE_TYPE") && map.get("ARCHIVE_CLASS_NODE_TYPE").toString().equals("2")){
			// if(null != map.get("ARCHIVE_CLASS_NODE_TYPE")){
			StringBuffer operateTypeCodes = new StringBuffer(); // 权限类型CODE串
			StringBuffer operateTypeNames = new StringBuffer(authString); // 权限类型NAME串
			// 遍历已注册的数据权限类型值
			int userAuthColSize = operateInfoMap.keySet().size();
			for (int j = 1; j <= userAuthColSize; j++) {
				String key = "A" + j;// 通用代码以字母A开头
				operateTypeCodes.append(key);
				// 最后一次不拼接逗号
				if (j != userAuthColSize) {
					operateTypeCodes.append(","); // 英文逗号
				}
			}
			// 0,0,0,0标识没有选中的记录，只保存有授权的记录
			// 根据targetType,targetId,authServiceId,res_code like 'code_%',dataAuth is not null判断是否存在条件信息
			int qualification = this.userAuthService.getLantopUserAuthSetExtendCount(targetType, targetId, "LANTOP_AUTH_SERVER_USERSET", (String) map.get("ID"));
			String cbbAuthResourceId = ""; // 权限资源信息ID
			for (int j = 0; j < authList.size(); j++) {
				Map<String, Object> auth = authList.get(j);
				String lacId = (String) auth.get("CODE");
				String authId = (String) auth.get("ID");
				if (lacId.equals(classId) && null != authId && !"".equals(authId) && !"null".equals(authId)) {
					cbbAuthResourceId = authId;
				}
			}
			// 只有存在授权的记录保存并且已存在sql条件设置
			if (operateTypeNames.indexOf("1") >= 0 || qualification > 0) {
				String code = (String) map.get("ID"); // 档案分类树节点ID
				String name = (String) map.get("ARCHIVE_CLASS_NODE_NAME"); // 档案分类树节点名称
				CbbAuthResource cbbAuthResource = new CbbAuthResource();
				cbbAuthResource.setId(cbbAuthResourceId);
				cbbAuthResource.setOrgId(orgId); // 组织ID
				cbbAuthResource.setDeptId(deptId); // 部门ID
				cbbAuthResource.setSysId(this.sysId); // 系统标识ID
				cbbAuthResource.setTargetType(targetType); // 授权维度类型
				cbbAuthResource.setTargetId(targetId); // 授权维度ID
				cbbAuthResource.setAuthServiceId("LANTOP_AUTH_SERVER_USERSET");
				cbbAuthResource.setCode(code); // 所选菜单ID
				cbbAuthResource.setName(name); // 所选菜单名称
				cbbAuthResource.setActionType(operateTypeCodes.toString()); // 授权类型CODE字符串
				cbbAuthResource.setOperateAuth(operateTypeNames.toString()); // 授权类型NAME字符串
				cbbAuthResources.add(cbbAuthResource);
			} else {
				// 2014年12月15日修改：之前已经存在授权，此次操作所有权限被取消，则要删除CBB_AUTH_RESOURCE表授权记录，同时删除LANTOP_USER_AUTH_SET_EXTEND表操作权限设置信息
				// 之前使用的先删除所有授权信息，在保存此次所有授权信息方法会导致已经设置过操作权限LANTOP_USER_AUTH_SET_EXTEND表的记录操作权限和授权表CBB_AUTH_RESOURCE记录脱离关系，导致所有关系丢失
				// 删除被取消授权或未被授权的记录，同时删除操作权限设置

				if (null != cbbAuthResourceId && !cbbAuthResourceId.equals("")) {
					// 存在授权信息，此次操作取消了所有授权信息
					delCbbAuthResourcesIds.append(cbbAuthResourceId);
					delCbbAuthResourcesIds.append(",");
				}
			}
		}
		try {
			if (null != delCbbAuthResourcesIds && !"".equals(delCbbAuthResourcesIds.toString())) {
				parameter.put("delCbbAuthResourcesIds", delCbbAuthResourcesIds.substring(0, delCbbAuthResourcesIds.length() - 1).toString()); // 要删除的权限资源信息ID串
			}
			this.userAuthService.saveResourceConfig(cbbAuthResources, parameter);

			Map<String, Object> nodesMap = new HashMap<String, Object>();
			if (!"".equals(nodeIdsSolr)) {
				nodesMap.put("tmNodes", targetNodeId);// nodeIdsSolr
			}
			if (!"".equals(nodeIdsQwSolr)) {
				nodesMap.put("qwNodes", targetNodeId);// nodeIdsQwSolr
			}
			if (!"".equals(nodeIdsSolr) || !"".equals(nodeIdsQwSolr)) {
				nodesMap.put("flag", "2");
				nodesMap.put("orgId", ThreadContextHelper.getOrgId());
				nodesMap.put("deptId", ThreadContextHelper.getDeptId());
				nodesMap.put("sysId", sysId);
				//动态更新索引
				solrService.insertSolrInfos(nodesMap);
				//this.updateSolrIndexTools(request, nodesMap);
			}
			maps.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			maps.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}
		return maps;
	}
	
	/**
	 * 跳转操作角色设置页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toOperateRoleSet")
	public ModelAndView toOperateRoleSet(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/OperateRoleSet");

		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		String targetIds = request.getParameter("targetIds"); // 已选角色ID串
		String targetNames = request.getParameter("targetNames"); // 已选角色名称串
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
		String resName = new String(request.getParameter("resName").getBytes("ISO-8859-1"), "UTF-8"); // 模块树名称
		String actionType = request.getParameter("actionType"); // 操作类型
		String operateAuth = request.getParameter("operateAuth"); // 操作权限
		String dialogId = request.getParameter("dialogId");

		mav.addObject("cbbAuthResourceId", cbbAuthResourceId);
		mav.addObject("targetType", targetType);
		mav.addObject("targetId", targetId);
		mav.addObject("targetIds", targetIds);
		mav.addObject("targetNames", targetNames);
		mav.addObject("authServiceId", authServiceId);
		mav.addObject("resCode", resCode);
		mav.addObject("resName", resName);
		mav.addObject("actionType", actionType);
		mav.addObject("operateAuth", operateAuth);
		mav.addObject("dialogId", dialogId);
		return mav;
	}

	/**
	 * 加载已设置角色
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/getAlreadySetRoles")
	public ModelAndView getAlreadySetRoles(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(null);

		String relTargetId = request.getParameter("relTargetId"); // 已设置角色ID串

		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		this.userAuthService.getAlreadySetRoles(page, relTargetId);
		mav.addObject("rows", page.getEntities());
		mav.addObject("total", page.getEntityCount());
		return mav;
	}

	/**
	 * 加载角色已定义操作
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/getRoleSetOperate")
	public ModelAndView getRoleSetOperate(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(null);

		String targetId = request.getParameter("targetId"); // 所选角色ID

		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("targetId", targetId);
		param.put("sysId", this.sysId);
		param.put("orgId", ThreadContextHelper.getOrgId());

		this.userAuthService.getRoleSetOperate(page, param);
		mav.addObject("rows", page.getEntities());
		mav.addObject("total", page.getEntityCount());
		return mav;
	}

	/**
	 * 加载没有设置角色
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/getNoSetRoles")
	public ModelAndView getNoSetRoles(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(null);

		String targetId = request.getParameter("targetId"); // 所选用户ID
		String code = request.getParameter("code"); // 节点ID

		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("sysId", this.sysId);
		param.put("orgId", ThreadContextHelper.getOrgId());
		param.put("targetId", targetId);
		param.put("code", code);

		this.userAuthService.getNoSetRoles(page, param);
		mav.addObject("targetId", targetId);
		mav.addObject("code", code);
		mav.addObject("rows", page.getEntities());
		mav.addObject("total", page.getEntityCount());
		return mav;
	}

	/**
	 * 跳转添加角色页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toAddRole")
	public ModelAndView toAddRole(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/AddRole");

		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
		String resName = new String(request.getParameter("resName").getBytes("ISO-8859-1"), "UTF-8"); // 模块树名称
		String actionType = request.getParameter("actionType"); // 操作类型
		String operateAuth = request.getParameter("operateAuth"); // 操作权限
		String dialogId = request.getParameter("dialogId");

		mav.addObject("cbbAuthResourceId", cbbAuthResourceId);
		mav.addObject("targetType", targetType);
		mav.addObject("targetId", targetId);
		mav.addObject("authServiceId", authServiceId);
		mav.addObject("resCode", resCode);
		mav.addObject("resName", resName);
		mav.addObject("actionType", actionType);
		mav.addObject("operateAuth", operateAuth);
		mav.addObject("dialogId", dialogId);
		return mav;
	}

	/**
	 * 角色操作设置：保存选择的角色
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/saveSelectRole")
	public ModelAndView saveSelectRole(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(null);

		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		String targetIds = request.getParameter("targetIds"); // 已选角色ID串
		String targetNames = request.getParameter("targetNames"); // 已选角色名称串
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
		String resName = request.getParameter("resName"); // 模块树名称
		String actionType = request.getParameter("actionType"); // 操作类型
		String operateAuth = request.getParameter("operateAuth"); // 操作权限
		String relTargetType = "1";

		StringBuffer relTargetId = new StringBuffer();
		StringBuffer relTargetName = new StringBuffer();

		try {
			// 获取已经设置的角色信息
			LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResourceId);
			if (null != lantopUserAuthSetExtend) {
				relTargetId.append(lantopUserAuthSetExtend.getRelTargetId());
				relTargetId.append(",");
				relTargetId.append(targetIds.substring(0, targetIds.length() - 1));
				relTargetName.append(lantopUserAuthSetExtend.getRelTargetName());
				relTargetName.append(",");
				relTargetName.append(targetNames.substring(0, targetNames.length() - 1));

				// 删除原始数据
				this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
			} else {
				relTargetId.append(targetIds.substring(0, targetIds.length() - 1));
				relTargetName.append(targetNames.substring(0, targetNames.length() - 1));
			}

			// 新增记录
			LantopUserAuthSetExtend newLantopUserAuthSetExtend = new LantopUserAuthSetExtend();
			newLantopUserAuthSetExtend.setOrgId(ThreadContextHelper.getOrgId());
			newLantopUserAuthSetExtend.setDeptId(ThreadContextHelper.getDeptId());
			newLantopUserAuthSetExtend.setSysId(this.sysId);
			newLantopUserAuthSetExtend.setCbbAuthResourceId(cbbAuthResourceId);
			newLantopUserAuthSetExtend.setTargetType(targetType);
			newLantopUserAuthSetExtend.setTargetId(targetId);
			newLantopUserAuthSetExtend.setAuthServiceId(authServiceId);
			newLantopUserAuthSetExtend.setResCode(resCode);
			newLantopUserAuthSetExtend.setResName(resName);
			newLantopUserAuthSetExtend.setActionType(actionType);
			newLantopUserAuthSetExtend.setOperateAuth(operateAuth);
			newLantopUserAuthSetExtend.setRelTargetType(relTargetType);
			newLantopUserAuthSetExtend.setRelTargetId(relTargetId.toString());
			newLantopUserAuthSetExtend.setRelTargetName(relTargetName.toString());
			this.userAuthService.insertLantopUserAuthSetExtend(newLantopUserAuthSetExtend);
			mav.addObject("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			mav.addObject("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}

		return mav;
	}

	/**
	 * 删除操作角色
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/delOperateRoleSet")
	public ModelAndView delOperateRoleSet(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(null);

		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源ID
		String allTargetIds = request.getParameter("allTargetIds"); // 所有角色
		String delTargetIds = request.getParameter("delTargetIds"); // 要删除的角色ID串
		delTargetIds = delTargetIds.substring(0, delTargetIds.length() - 1); // 去掉末尾逗号
		String delTargetNames = request.getParameter("delTargetNames"); // 要删除的角色名称串
		delTargetNames = delTargetNames.substring(0, delTargetNames.length() - 1); // 去掉末尾逗号

		try {
			LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResourceId);
			int targetIdIndex = allTargetIds.indexOf(",");
			if (targetIdIndex < 0) {
				// targetIdIndex小于0,只有一个角色，直接删除记录
				this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
			} else {
				// targetIdIndex大于0
				if (allTargetIds.equals(delTargetIds)) {
					// 要删除的角色ID串等于所有角色ID串，删除记录
					this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
				} else {
					// 更新记录REL_TARGET_ID、REL_TARGET_NAME字段
					this.userAuthService.delRoleSet(lantopUserAuthSetExtend, delTargetIds, delTargetNames);
				}
			}
			mav.addObject("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			mav.addObject("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}

		return mav;
	}

	/**
	 * 跳转条目权限设置页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toEntryAuthSetJsp")
	public ModelAndView toEntryAuthSetJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/EntryAuthSet");

		String dialogId = request.getParameter("dialogId");
		String nodeIds = request.getParameter("nodeIds"); // 所选档案分类第一个树节点ID
		String nodeId[] = nodeIds.split(",");
		String targetId = request.getParameter("targetId");
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		// 条目类型
		List<Map<String, Object>> entryTypeList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> treeNodeList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(ThreadContextHelper.getOrgId(),
				ThreadContextHelper.getDeptId(), this.sysId, nodeId[0], "");

		Map<String, Object> entryTypeMap = new HashMap<String, Object>();
		entryTypeMap.put("0", "电子文件");
		entryTypeMap.put("1", "文件级");
		entryTypeMap.put("2", "案卷级");
		entryTypeMap.put("3", "其它");

		// 电子文件为固定值
		Map<String, Object> electronicEntryTypeMap = new HashMap<String, Object>();
		electronicEntryTypeMap.put("code", 0);
		electronicEntryTypeMap.put("name", entryTypeMap.get("0"));
		entryTypeList.add(electronicEntryTypeMap);

		for (int i = 1; i <= treeNodeList.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", i);
			map.put("name", entryTypeMap.get(i + ""));
			entryTypeList.add(map);
		}

		// 动态生成操作权限列
		Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
		List<Map<String, String>> userAuthColList = new ArrayList<Map<String, String>>();
		int userAuthColSize = operateInfoMap.keySet().size();
		for (int i = 1; i <= userAuthColSize; i++) {
			if (i > 9) {
				// 这种写法目前最多支持9中权限，如果要支持更多权限，jsp页面中的脚本方法同时也需要修改
				break;
			}
			Map<String, String> map = new HashMap<String, String>();
			String key = "A" + i;// 通用代码以字母A开头，按顺序1、2.。。排列，这种写法目前最多支持9中权限，如果要支持更多权限，jsp页面中的脚本方法同时也需要修改
			map.put("code", key);
			map.put("name", operateInfoMap.get(key));
			userAuthColList.add(map);
		}

		mav.addObject("dialogId", dialogId);
		mav.addObject("userAuthColList", userAuthColList);
		mav.addObject("userAuthColSize", userAuthColSize);
		mav.addObject("entryTypeList", entryTypeList);
		mav.addObject("nodeIds", nodeIds);
		mav.addObject("targetId", targetId);
		mav.addObject("targetType", targetType);
		mav.addObject("rcdDataType", treeNodeList.size()); // 条目类型数量等于是条目类型的code值
		mav.addObject("authCount", userAuthColList.size());
		return mav;
	}

	/**
	 * 获取待选择条目列表
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/getWaitSelectEntry")
	@ResponseBody
	public Map<String,Object> getWaitSelectEntry(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String entryType = request.getParameter("entryType"); // 条目类型
		String nodeIds = request.getParameter("nodeIds");
		String nodeId[] = nodeIds.split(",");
		nodeIds = "'" + nodeIds + "'";
		nodeIds = nodeIds.replace(",", "','");
		String targetId = request.getParameter("targetId");
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";

		// 查询参数
		String json = request.getParameter("param");
		Map<String, Object> searchMap = new HashMap<String, Object>();
		if (json != null && !"".equals(json)) {
			searchMap = JsonHelper.getInstance().readValue(json, Map.class);
		}

		List<Map<String, Object>> treeNodeList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(ThreadContextHelper.getOrgId(),
				ThreadContextHelper.getDeptId(), this.sysId, nodeId[0], "");

		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		if ("0".equals(entryType)) {
			// 电子文件
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("tableList", treeNodeList);
			param.put("orgId", ThreadContextHelper.getOrgId());
			param.put("sysId", this.sysId);
			param.put("nodeIds", nodeIds);
			param.put("targetType", targetType);
			param.put("targetId", targetId);
			param.put("searchMap", searchMap);
			this.userAuthService.getElectronicWaitSelectEntry(page, param);
		} else {
			// 非电子文件
			String tableName = "";
			String tableId = "";
			int nodeNum = treeNodeList.size();
			// 第一次进页面，没有选择条目类型。条目类型默认值为最大级别的表明
			if (null == entryType || "".equals(entryType)) {
				tableName = (String) treeNodeList.get(0).get("TABLE_NAME"); // 表明
				tableId = (String) treeNodeList.get(0).get("ID"); // 表明
			} else {
				tableName = (String) treeNodeList.get(nodeNum - Integer.parseInt(entryType)).get("TABLE_NAME"); // 表明
				tableId = (String) treeNodeList.get(nodeNum - Integer.parseInt(entryType)).get("ID"); // 物理表ID
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("tableName", tableName);
			param.put("tableId", tableId);
			param.put("orgId", ThreadContextHelper.getOrgId());
			param.put("sysId", this.sysId);
			param.put("nodeIds", nodeIds);
			param.put("targetType", targetType);
			param.put("targetId", targetId);
			param.put("searchMap", searchMap);
			this.userAuthService.getNotElectronicWaitSelectEntry(page, param);
		}

		map.put("rows", page.getEntities());
		map.put("total", page.getEntityCount());
		return map;
	}

	/**
	 * 加载已设置权限条目
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/getAuthEntry")
	@ResponseBody
	public Map<String,Object> getAuthEntry(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String targetId = request.getParameter("targetId");
		String nodeIds = "'" + request.getParameter("nodeIds") + "'";
		nodeIds = nodeIds.replace(",", "','"); // 构造sql查询IN格式

		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
		int userAuthColSize = operateInfoMap.keySet().size();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userAuthColSize", userAuthColSize);
		param.put("orgId", ThreadContextHelper.getOrgId());
		param.put("sysId", this.sysId);
		param.put("targetId", targetId);
		param.put("targetType", targetType);
		param.put("nodeIds", nodeIds);

		this.userAuthService.getAuthEntry(page, param);

		map.put("rows", page.getEntities());
		map.put("total", page.getEntityCount());

		return map;
	}

	/**
	 * 保存权限设置条目
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/saveAuthEntry")
	@ResponseBody
	public Map<String,Object> saveAuthEntry(HttpServletRequest request) throws Exception {
		Map<String,Object> maps = new HashMap<>();
		String orgId = ThreadContextHelper.getOrgId();
		String deptId = ThreadContextHelper.getDeptId();
		String nodeIds = request.getParameter("nodeIds");       //节点ID
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		String targetId = request.getParameter("targetId"); // 授权维度ID：用户ID
		//String rcdDataType = request.getParameter("rcdDataType"); // 所选条目类型下拉框代码值
		String datas = request.getParameter("datas"); // 资源列表
		String startDate = request.getParameter("startDate"); // 开始时间
		String endDate = request.getParameter("endDate"); // 结束时间
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("orgId", ThreadContextHelper.getOrgId());
		parameter.put("sysId", this.sysId);
		parameter.put("targetId", targetId);
		parameter.put("serviceId", "LANTOP_AUTH_SERVER_USERSET");

		// 条目权限设置
		Map<String, Object>[] authEntryDatas = JsonUtils.newInstance().Json2Bean2DataGrid(datas, HashMap[].class);
		Map<String, Object> map = null;
		// 已经注册的数据权限类型
		Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
		// 遍历已注册的数据权限类型值
		int userAuthColSize = operateInfoMap.keySet().size();
		List<LantopUserAuthExtendData> lantopUserAuthExtendDatas = new ArrayList<LantopUserAuthExtendData>();
		for (int i = 0; i < authEntryDatas.length; i++) {
			map = authEntryDatas[i];
			StringBuffer operateTypeCodes = new StringBuffer(); // 权限类型CODE串
			StringBuffer operateTypeNames = new StringBuffer(); // 权限类型NAME串

			for (int j = 1; j <= userAuthColSize; j++) {
				String key = "A" + j;// 通用代码以字母A开头
				String operateType = (String) map.get(key); // 权限类型值
				operateType = operateType.replace(key, ""); // 动态列区分需要每个列的默认值为自己本身的列名，这里获取到值后要清空标识的列名
				operateTypeCodes.append(key);
				operateTypeNames.append(operateType);
				// 最后一次不拼接逗号
				if (j != userAuthColSize) {
					operateTypeCodes.append(","); // 英文逗号
					operateTypeNames.append(","); // 英文逗号
				}
			}
			LantopUserAuthExtendData lantopUserAuthExtendData = new LantopUserAuthExtendData();
			lantopUserAuthExtendData.setId((String) map.get("ID"));
			lantopUserAuthExtendData.setOrgId(ThreadContextHelper.getOrgId());
			lantopUserAuthExtendData.setDeptId(ThreadContextHelper.getDeptId());
			lantopUserAuthExtendData.setSysId(this.sysId);
			lantopUserAuthExtendData.setTargetType(targetType);
			lantopUserAuthExtendData.setTargetId(targetId);
			lantopUserAuthExtendData.setAuthServiceId("LANTOP_AUTH_SERVER_USERSET");
			lantopUserAuthExtendData.setArchiveClassId((String) map.get("ARCHIVE_CLASS_ID"));
			lantopUserAuthExtendData.setRcdDataType((String) map.get("RCD_DATA_TYPE"));
			lantopUserAuthExtendData.setArchiveTableId((String) map.get("TABLE_ID"));
			lantopUserAuthExtendData.setResCode((String) map.get("RES_CODE")); // 新添加记录将左侧记录ID写入右侧datagrid的RES_CODE列中
			lantopUserAuthExtendData.setResName((String) map.get("RES_CODE"));
			lantopUserAuthExtendData.setActionType(operateTypeCodes.toString());
			lantopUserAuthExtendData.setOperateAuth(operateTypeNames.toString());
			lantopUserAuthExtendData.setWjh((String) map.get("WJH"));
			lantopUserAuthExtendData.setTm((String) map.get("TM"));
			lantopUserAuthExtendData.setAttribute01((String) map.get("ATTACH_NAME")); // 电子文件名称
			lantopUserAuthExtendData.setStartDate(ComUtil.String2Date(startDate)); // 开始时间
			lantopUserAuthExtendData.setEndDate(ComUtil.String2Date(endDate)); // 结束时间
			lantopUserAuthExtendDatas.add(lantopUserAuthExtendData);
		}
		try {
			//保存条目授权信息
			this.userAuthService.saveAuthEntry(lantopUserAuthExtendDatas, parameter);
			//根据节点id获取条目权限设置信息
			List<Map<String, Object>> authExtendDatas = this.userAuthService.getUserAuthExtendDatasByNodeId(nodeIds);
			//全局授权信息
			Map<String, Object> authmlParam = new HashMap<String, Object>();
			List<Map<String, Object>> mlList = new ArrayList<Map<String, Object>>();
			List<String> dataIds = new ArrayList<String>();
			//获取当前节点
			for (int i = 0; i < authExtendDatas.size(); i++) {
				Map<String, Object> authExtendMap = authExtendDatas.get(i);
				String dataId = (String) authExtendMap.get("RES_CODE");
				String tableId = (String) authExtendMap.get("ARCHIVE_TABLE_ID");
				if (!dataIds.contains(dataId)) {
					dataIds.add(dataId);
					List<Map<String, Object>> ll = this.commTableManagerIntfsService.getCbbTableAndColumnsByTabIdByIntfs(tableId);
					String tableName = "";
					if (ll.size() > 0) {
						tableName = (String)ll.get(0).get("TABLE_NAME");
					}
					Map<String, Object> mapp = new HashMap<String, Object>();
					mapp.put("nodeId", nodeIds);
					mapp.put("tableId", tableId);
					mapp.put("tableName", tableName);
					mapp.put("recordId", (String) authExtendMap.get("RES_CODE"));
					mlList.add(mapp);
					//获取操作权限字符串
					//String operateAuth = (String) authExtendMap.get("OPERATE_AUTH");
					//String[] operates = operateAuth.split(",");
					String rcdDataType = (String) authExtendMap.get("RCD_DATA_TYPE");
					if ("0".equals(rcdDataType)) {
						SysFileUpload sfu =  this.sfuService.getSysFileUploadById(dataId);
						Map<String, Object> mapRecord = new HashMap<String, Object>();
						mapRecord.put("nodeId", nodeIds);
						mapRecord.put("tableId", tableId);
						mapRecord.put("tableName", tableName);
						mapRecord.put("recordId", sfu.getFILE_BUSINESS_ID());
						mlList.add(mapRecord);
					} else {
						List<Map<String, Object>> attachList = fileUploadIntfsService.getAttachmentsByRecordId(dataId);
						for (int k = 0; k < attachList.size(); k++) {
							Map<String, Object> attachMap = attachList.get(k);
							String attachId = (String) attachMap.get("ID");
							Map<String, Object> mapAttach = new HashMap<String, Object>();
							mapAttach.put("nodeId", nodeIds);
							mapAttach.put("tableId", tableId);
							mapAttach.put("tableName", tableName);
							mapAttach.put("recordId", attachId);
							mlList.add(mapAttach);
						}
					}
				}
			}

			authmlParam.put("list", mlList);
			// 获取源数据和继承数据授权信息
			Map<String, Object> authmlMap = userAuthIntfsService.getUserIdsAuthDatasByRecord(authmlParam);
			List<Map<String, Object>> tableInfos = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeIds, "");
			Map<String, String> tableFlagMap = new HashMap<String, String>();
			for (int i = 0; i < tableInfos.size(); i++) {
				Map<String, Object> tableInfo = tableInfos.get(i);
				String infoTableId = (String) tableInfo.get("ID");
				if (tableInfos.size() == 1) {
					tableFlagMap.put(infoTableId, "lantop_wjml");
				} else {
					if (null != tableInfo.get("TAB_FLAG") && !"".equals(tableInfo.get("TAB_FLAG"))) {
						tableFlagMap.put(infoTableId, "lantop_ajml");
					} else {
						tableFlagMap.put(infoTableId, "lantop_wjml");
					}
					
				}
			}
			//权限授权集合
			Map<String, Map<String, String>> authMap = new HashMap<String, Map<String, String>>();
			//附件不可浏览数据集合
			Map<String, String> notSearchMap = new HashMap<String, String>();
			//循环数据进行授权
			for (int i = 0; i < dataIds.size(); i++) {
				String dataId = dataIds.get(i);
				Map<String, String> recordMap = new HashMap<String, String>();
				//电子文件授权用户ids
				String qwnrUser = "";
				//文件级授权用户ids
				String wjmlUser = "";
				//案卷级授权用户ids
				String ajmlUser = "";
				//根据条目或者附件id,获取授权用户字符串
				String authUserIds = (String) authmlMap.get(dataId);
				//授权用户字符串
				if (null != authUserIds && !"".equals(authUserIds)) {
					authUserIds += ",";
				}
				
				//当前数据id的数据类型
				String currentDataType = "";
				for (int j = 0; j < authExtendDatas.size(); j++) {
					Map<String, Object> authExtendMap = authExtendDatas.get(j);
					String currentTableId = (String) authExtendMap.get("ARCHIVE_TABLE_ID");
							
					//获取操作权限字符串
					String operateAuth = (String) authExtendMap.get("OPERATE_AUTH");
					//下标0为条目浏览,1为全文浏览
					String[] operateAuthArray = operateAuth.split(",");
					//数据id或条目id
					String dId = (String) authExtendMap.get("RES_CODE");
					if (dataId.equals(dId)) {
						//授权用户id
						String userId = (String) authExtendMap.get("TARGET_ID");
						//条目类型: 0电子文件 1文件级 2案卷级
						String dataType = (String) authExtendMap.get("RCD_DATA_TYPE");
						currentDataType = dataType;
						if ("0".equals(dataType)) {
							//如果是附件类型,且操作权限为条目可以浏览,需要反查条目的id进行授权
							if ("1".equals(operateAuthArray[0])) {
								SysFileUpload sfu =  this.sfuService.getSysFileUploadById(dId);
								//当前附件所对应的数据id
								String currentDataId = sfu.getFILE_BUSINESS_ID();
								//判断当前授权集合中是否已经存在当前附件所对应的数据id的授权信息
								if (authMap.containsKey(currentDataId)) {
									//获取已授权数据
									Map<String, String> currentRecordMap = authMap.get(currentDataId);
									if (currentRecordMap.containsKey("lantop_wjml")) {
										String currentAuthString = currentRecordMap.get("lantop_wjml");
										if (null != currentAuthString && !"".equals(currentAuthString)) {
											String[] authStringArray = currentAuthString.split(",");
											//判断授权用户是否存在当前用户
											if (Arrays.asList(authStringArray).contains(userId) == false) {
												currentAuthString += "," + userId;
											} else {
												currentAuthString = userId;
											}
										} else {
											currentAuthString = userId;
										}
										currentRecordMap.put("lantop_wjml", currentAuthString);
									} else {
										String currentAuthString = currentRecordMap.get("lantop_ajml");
										if (null != currentAuthString && !"".equals(currentAuthString)) {
											String[] authStringArray = currentAuthString.split(",");
											//判断授权用户是否存在当前用户
											if (Arrays.asList(authStringArray).contains(userId) == false) {
												currentAuthString += "," + userId;
											} else {
												currentAuthString = userId;
											}
										} else {
											currentAuthString = userId;
										}
										currentRecordMap.put("lantop_ajml", currentAuthString);
									}
								} else {
									//在源授权map中查询是否存在当前附件对应的数据id的授权
									if (dataIds.contains(currentDataId)) {
										//根据条目或者附件id,获取授权用户字符串
										String currentAuthString = (String) authmlMap.get(currentDataId);
										if (null != currentAuthString && !"".equals(currentAuthString)) {
											String[] authStringArray = currentAuthString.split(",");
											//判断此授权用户字符串是否存在当前用户id
											if (Arrays.asList(authStringArray).contains(userId) == false) {
												if (null != currentAuthString && !"".equals(currentAuthString)) {
													currentAuthString += "," + userId;
												} else {
													currentAuthString = userId;
												}
											}
										} else {
											currentAuthString = userId;
										}
										//将授权用户字符串赋值到源授权map中,再次循环到当前数据id时,进行授权
										authmlMap.put(currentDataId, currentAuthString);
									} else {
										//数据循环中没有当前数据id,则添加到已授权map中
										String currentAuthString = (String) authmlMap.get(currentDataId);
										Map<String, String> currentMap = new HashMap<String, String>();
										if (null != currentAuthString && !"".equals(currentAuthString)) {
											String[] authStringArray = currentAuthString.split(",");
											if (Arrays.asList(authStringArray).contains(userId) == false) {
												currentAuthString += "," + userId;
											} else {
												currentAuthString = userId;
											}
										} else {
											currentAuthString = userId;
										}
										//将授权用户字符串赋值到已授权map中
										currentMap.put(tableFlagMap.get(currentTableId), currentAuthString);
										authMap.put(currentDataId, currentMap);
									}
								}
							}
							String[] authUserIdsArray = authUserIds.split(",");
							//判断授权用户字符串中是否存在当前用户
							if (Arrays.asList(authUserIdsArray).contains(userId) == false && "1".equals(operateAuthArray[1])) {
								qwnrUser += userId + ",";
							}
							if ("0".equals(operateAuthArray[1])) {
								notSearchMap.put(dataId, userId);
							}
						} else if ("1".equals(dataType)) {
							if ("1".equals(operateAuthArray[0])) {
								String[] authUserIdsArray = authUserIds.split(",");
								if (Arrays.asList(authUserIdsArray).contains(userId) == false) {
									wjmlUser += userId + ",";
								}
								//判断当前数据是否有全文浏览权限
								if ("1".equals(operateAuthArray[1])) {
									//当前数据id下有全文浏览权限,则通过数据id获取该条目下的附件集合
									List<Map<String, Object>> attachList = fileUploadIntfsService.getAttachmentsByRecordId(dId);
									for (int k = 0; k < attachList.size(); k++) {
										Map<String, Object> attachMap = attachList.get(k);
										String attachId = (String) attachMap.get("ID");
										//判断已授权map中是否存在该附件的授权信息
										if (authMap.containsKey(attachId)) {
											//获取已授权数据map
											Map<String, String> currentRecordMap = authMap.get(attachId);
											//获取已授权用户ids
											String currentAuthString = currentRecordMap.get("lantop_qwnr");
											if (null != currentAuthString && !"".equals(currentAuthString)) {
												String[] authStringArray = currentAuthString.split(",");
												//判断已授权用户中是否存在当前用户
												if (Arrays.asList(authStringArray).contains(userId) == false) {
													//添加当前用户到已授权用户中
													currentAuthString += "," + userId;
												} else {
													currentAuthString = userId;
												}
											} else {
												currentAuthString = userId;
											}
											currentRecordMap.put(attachId, currentAuthString);
										} else {
											//判断数据中是否有该附件id
											if (dataIds.contains(attachId)) {
												//如果源授权map中存在该附件id信息
												String currentAuthString = (String) authmlMap.get(attachId);
												if (null != currentAuthString && !"".equals(currentAuthString)) {
													String[] authStringArray = currentAuthString.split(",");
													//判断该附件id在源授权用户中是否存在
													if (Arrays.asList(authStringArray).contains(userId) == false) {
														currentAuthString += "," + userId;
													} else {
														currentAuthString = userId;
													}
												} else {
													currentAuthString = userId;
												}
												//将授权用户字符串赋值到源授权map中
												authmlMap.put(attachId, currentAuthString);
											} else {
												//数据循环中没有当前数据id,则添加到已授权map中
												String currentAuthString = (String) authmlMap.get(attachId);
												Map<String, String> currentMap = new HashMap<String, String>();
												if (null != currentAuthString && !"".equals(currentAuthString)) {
													String[] authStringArray = currentAuthString.split(",");
													if (Arrays.asList(authStringArray).contains(userId) == false) {
														currentAuthString += "," + userId;
													} else {
														currentAuthString = userId;
													}
												} else {
													currentAuthString = userId;
												}
												//将授权用户字符串赋值到已授权map中
												currentMap.put("lantop_qwnr", currentAuthString);
												authMap.put(attachId, currentMap);
											}
										}
									}
								} else {
									List<Map<String, Object>> attachList = fileUploadIntfsService.getAttachmentsByRecordId(dId);
									for (int k = 0; k < attachList.size(); k++) {
										Map<String, Object> attachMap = attachList.get(k);
										String attachId = (String) attachMap.get("ID");
										notSearchMap.put(attachId, userId);
									}
								}
							}
						} else {
							if ("1".equals(operateAuthArray[0])) {
								String[] authUserIdsArray = authUserIds.split(",");
								if (Arrays.asList(authUserIdsArray).contains(userId) == false) {
									ajmlUser += userId + ",";
								}
								//判断当前数据是否有全文浏览权限
								if ("1".equals(operateAuthArray[1])) {
									//当前数据id下有全文浏览权限,则通过数据id获取该条目下的附件集合
									List<Map<String, Object>> attachList = fileUploadIntfsService.getAttachmentsByRecordId(dId);
									for (int k = 0; k < attachList.size(); k++) {
										Map<String, Object> attachMap = attachList.get(k);
										String attachId = (String) attachMap.get("ID");
										//判断已授权map中是否存在该附件的授权信息
										if (authMap.containsKey(attachId)) {
											//获取已授权数据map
											Map<String, String> currentRecordMap = authMap.get(attachId);
											//获取已授权用户ids
											String currentAuthString = currentRecordMap.get("lantop_qwnr");
											if (null != currentAuthString && !"".equals(currentAuthString)) {
												String[] authStringArray = currentAuthString.split(",");
												//判断已授权用户中是否存在当前用户
												if (Arrays.asList(authStringArray).contains(userId) == false) {
													//添加当前用户到已授权用户中
													currentAuthString += "," + userId;
												} else {
													currentAuthString = userId;
												}
											} else {
												currentAuthString = userId;
											}
											currentRecordMap.put(attachId, currentAuthString);
										} else {
											//已授权map中不存在,在源授权信息中查看是否存在. 存在则进行授权信息补充,不存在则进行授权信息添加
											if (dataIds.contains(attachId)) {
												//如果源授权map中存在该附件id信息
												String currentAuthString = (String) authmlMap.get(attachId);
												//判断该附件id在源授权用户中是否存在
												if (null != currentAuthString && !"".equals(currentAuthString)) {
													String[] authStringArray = currentAuthString.split(",");
													if (Arrays.asList(authStringArray).contains(userId) == false) {
														//添加当前用户到已授权用户中
														currentAuthString += "," + userId;
													} else {
														currentAuthString = userId;
													}
												} else {
													currentAuthString = userId;
												}
												//将授权用户字符串赋值到源授权map中
												authmlMap.put(attachId, currentAuthString);
											} else {
												//数据循环中没有当前数据id,则添加到已授权map中
												String currentAuthString = (String) authmlMap.get(attachId);
												Map<String, String> currentMap = new HashMap<String, String>();
												if (null != currentAuthString && !"".equals(currentAuthString)) {
													String[] authStringArray = currentAuthString.split(",");
													if (Arrays.asList(authStringArray).contains(userId) == false) {
														currentAuthString += "," + userId;
													} else {
														currentAuthString = userId;
													}
												} else {
													currentAuthString = userId;
												}
												currentMap.put(tableFlagMap.get(currentTableId), currentAuthString);
												authMap.put(attachId, currentMap);
											}
										}
									}
								}
							}
						}
					}
				}
				if ("0".equals(currentDataType)) {
					qwnrUser = authUserIds + qwnrUser;
				} else if ("1".equals(currentDataType)) {
					wjmlUser= authUserIds + wjmlUser;
				} else {
					ajmlUser = authUserIds + ajmlUser;
				}
				if (!"".equals(qwnrUser)) {
					qwnrUser = qwnrUser.substring(0, qwnrUser.length() - 1);
					recordMap.put("lantop_qwnr", qwnrUser);
				}
				if (!"".equals(wjmlUser)) {
					wjmlUser = wjmlUser.substring(0, wjmlUser.length() - 1);
					recordMap.put("lantop_wjml", wjmlUser);
				}
				if (!"".equals(ajmlUser)) {
					ajmlUser = ajmlUser.substring(0, ajmlUser.length() - 1);
					recordMap.put("lantop_ajml", ajmlUser);
				}
				authMap.put(dataId, recordMap);
			}
			//将用户不可浏览附件清除权限
			Iterator<String> it = notSearchMap.keySet().iterator();
			while (it.hasNext()) {
				String dataId = it.next();
				String userId = notSearchMap.get(dataId);
				if (authMap.containsKey(dataId)) {
					Map<String, String> authChildMap = authMap.get(dataId);
					Iterator<String> childIt = authChildMap.keySet().iterator();
					while (childIt.hasNext()) {
						String key = childIt.next();
						String authUsers = authChildMap.get(key);
						String[] authUsersArray = authUsers.split(",");
						List<String> authUsersList = Arrays.asList(authUsersArray);
						if (authUsersList.contains(userId)) {
							authUsers = "";
							for (int i = 0; i < authUsersList.size(); i++) {
								String curUser = authUsersList.get(i);
								if (!userId.equals(curUser)) {
									authUsers += curUser;
								}
								if (i != authUsersList.size() - 1) {
									authUsers += ",";
								}
							}
						}
						authChildMap.put(key, authUsers);
					}
				} else {
					if (authmlMap.containsKey(dataId)) {
						String childAuthString = (String) authmlMap.get(dataId);
						if (null != childAuthString && !"".equals(childAuthString)) {
							String[] childAuthStringArray = childAuthString.split(",");
							List<String> authUsersList = Arrays.asList(childAuthStringArray);
							if (authUsersList.contains(userId)) {
								childAuthString = "";
								for (int i = 0; i < authUsersList.size(); i++) {
									String curUser = authUsersList.get(i);
									if (!userId.equals(curUser)) {
										childAuthString += curUser;
									}
									if (i != authUsersList.size() - 1) {
										childAuthString += ",";
									}
								}
								Map<String, String> authUserMap = new HashMap<String, String>();
								authUserMap.put("lantop_qwnr", childAuthString);
								authMap.put(dataId, authUserMap);
							} else {
								Map<String, String> authUserMap = new HashMap<String, String>();
								authUserMap.put("lantop_qwnr", childAuthString);
								authMap.put(dataId, authUserMap);
							}
						}
					}
				}
			}
			//获取工程目录路径
			String path = request.getSession().getServletContext().getRealPath("/");
			if (!path.endsWith(File.separator)) {
				path = path + File.separator;
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orgId", orgId);
			param.put("deptId", deptId);
			param.put("sysId", sysId);
			param.put("path", path);
			
			/*final Map<String, Map<String, String>> rMap = authMap;
			final Map<String, Object> pMap = param;
			Thread t = new Thread() {

				public void run() {
					try {
						cbbSearchengIntfsService.updateSolrIndex(rMap, pMap);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			t.start();
			System.out.println("动态更新检索的索引---success!");*/
			
			Map<String,Object> nodesMap = new HashMap<String,Object>();
			if(!"".equals(nodeIds)){
				nodesMap.put("tmNodes", nodeIds);
				nodesMap.put("qwNodes", nodeIds);
				nodesMap.put("flag", "2");
				nodesMap.put("orgId", ThreadContextHelper.getOrgId());
				nodesMap.put("deptId", ThreadContextHelper.getDeptId());
				nodesMap.put("sysId", sysId);
				solrService.insertSolrInfos(nodesMap);
			  //this.updateSolrIndexTools(request,nodesMap);	 
			}
			maps.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			maps.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}
		return maps;
	}

	/**
	 * 删除条目权限设置
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/delAuthEntry")
	@ResponseBody
	public Map<String,Object> delAuthEntry(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String nodeIds = request.getParameter("nodeIds");       //节点ID
		String ids = "'" + request.getParameter("ids") + "'";
		ids = ids.replace(",", "','");
		try {
			this.userAuthService.delAuthEntry(ids);
			Map<String,Object> nodesMap = new HashMap<String,Object>();
			if(!"".equals(nodeIds)){
				nodesMap.put("tmNodes", nodeIds);
				nodesMap.put("qwNodes", nodeIds);
				nodesMap.put("flag", "2");
				nodesMap.put("orgId", ThreadContextHelper.getOrgId());
				nodesMap.put("deptId", ThreadContextHelper.getDeptId());
				nodesMap.put("sysId", sysId);
				solrService.insertSolrInfos(nodesMap);
			    //this.updateSolrIndexTools(request,nodesMap);	 
			}
			map.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("flag", OpResult.failure.ordinal());
		}
		return map;
	}

	/**
	 * 跳转新增条件页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toAddQualificationJsp")
	public ModelAndView toAddQualificationJsp(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> authTypeList = sysLookupLoaderI.getLookUpListByType("LANTOP_AUTH_TYPE");
		Collection<SysLookupSimpleVo> operCharacterList = sysLookupLoaderI.getLookUpListByType("CBB_OPER_CHARACTER");
		Collection<SysLookupSimpleVo> logicOperList = sysLookupLoaderI.getLookUpListByType("CBB_LOGIC_OPER");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/AddQualification");

		String dialogId = request.getParameter("dialogId");
		String nodeIds = request.getParameter("nodeIds");
		String[] nodeId = nodeIds.split(",");
		String nodeNames = URLDecoder.decode(request.getParameter("nodeNames"), "utf-8"); // 所选树节点名称串
		
		String targetId = request.getParameter("targetId"); // 用户ID
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String authServiceId = request.getParameter("authServiceId"); // 服务ID

		// 数据表
		List<Map<String, Object>> tableList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(),
				this.sysId, nodeId[0], "");
		// 获取数据表下拉框
		StringBuffer sbtable = new StringBuffer();
		sbtable.append("[");
		Iterator<Map<String, Object>> tableIt = tableList.iterator();
		int index = 0;
		while (tableIt.hasNext()) {
			Map<String, Object> map = tableIt.next();
			String id = (String) map.get("ID");
			String text = (String) map.get("TABLE_TITLE");
			sbtable.append("{id:'" + id + "',");
			sbtable.append("text:'" + text + "'");
			if (index == 0) {
				sbtable.append(",selected:true");
			}
			sbtable.append("},");
			index++;
		}
		String table = sbtable.subSequence(0, sbtable.length() - 1).toString();
		table = table + "]";

		// 权限类型
		StringBuffer sbAuthType = new StringBuffer();
		sbAuthType.append("[");
		Iterator<SysLookupSimpleVo> authTypeIt = authTypeList.iterator();
		index = 0;
		while (authTypeIt.hasNext()) {
			SysLookupSimpleVo simpleVo = authTypeIt.next();
			String id = simpleVo.getLookupCode();
			if(id.equals("A3")){
				index++;
				continue;
			}
			String text = simpleVo.getLookupName();
			sbAuthType.append("{id:'" + id + "',");
			sbAuthType.append("text:'" + text + "'");
			if (index == 0) {
				sbAuthType.append(",selected:true");
			}
			sbAuthType.append("},");
			index++;
		}
		String authType = sbAuthType.subSequence(0, sbAuthType.length() - 1).toString();
		authType = authType + "]";

		// 获取运算符下拉框数据
		StringBuffer sbysf = new StringBuffer();
		sbysf.append("[");
		Iterator<SysLookupSimpleVo> itysf = operCharacterList.iterator();
		while (itysf.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) itysf.next();
			String id = sysLookupSimpleVo.getLookupCode();
			String text = sysLookupSimpleVo.getLookupName();
			sbysf.append("{id:'" + id + "',");
			sbysf.append("text:'" + text + "'");
			sbysf.append("},");
		}
		String ysf = sbysf.subSequence(0, sbysf.length() - 1).toString();
		ysf = ysf + "]";

		// 获取并且/或者下拉框数据
		StringBuffer sbljgx = new StringBuffer();
		sbljgx.append("[");
		Iterator<SysLookupSimpleVo> ithzbq = logicOperList.iterator();
		while (ithzbq.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) ithzbq.next();
			String idhzbq = sysLookupSimpleVo.getLookupCode();
			String texthzbq = sysLookupSimpleVo.getLookupName();
			sbljgx.append("{id:'" + idhzbq + "',");
			sbljgx.append("text:'" + texthzbq + "'");
			sbljgx.append("},");
		}
		String hzbq = sbljgx.subSequence(0, sbljgx.length() - 1).toString();
		hzbq = hzbq + "]";

		mav.addObject("dialogId", dialogId);
		mav.addObject("nodeIds", nodeIds); // 父页面所选节点
		mav.addObject("table", table); // 数据表
		mav.addObject("authTypeListStr", authType); // 权限类型
		mav.addObject("ysf", ysf); // 运算符
		mav.addObject("ljgx", hzbq); // 逻辑关系
		mav.addObject("nodeNames", nodeNames);
		mav.addObject("targetId", targetId);
		mav.addObject("targetType", targetType);
		mav.addObject("authServiceId", authServiceId);
		return mav;
	}

	/**
	 * 获取数据表对应的字段
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/getTableCol")
	@ResponseBody
	public Map<String,Object> getTableCol(HttpServletRequest request) throws Exception {
		Map<String,Object> maps = new HashMap<>();

		String nodeIds = request.getParameter("nodeIds");
		String[] nodeId = nodeIds.split(",");
		String tableId = request.getParameter("tableId");

		List<Map<String, Object>> colList = this.commTableManagerIntfsService.getCbbTabColumnsByIntfs(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(),
				this.sysId, nodeId[0], tableId);
		// 获取数据表下拉框
		StringBuffer sbcol = new StringBuffer();
		sbcol.append("[");
		Iterator<Map<String, Object>> colIt = colList.iterator();
		while (colIt.hasNext()) {
			Map<String, Object> map = colIt.next();
			String id = (String) map.get("COL_NAME");
			String text = (String) map.get("COL_LABEL");
			String type = (String) map.get("COL_TYPE");
			sbcol.append("{id:'" + id + "',");
			sbcol.append("text:'" + text + "',");
			sbcol.append("type:'" + type + "'");
			sbcol.append("},");
		}
		String cols = sbcol.subSequence(0, sbcol.length() - 1).toString();
		cols = null == cols || "".equals(cols) ? "[]" : cols + "]";

		maps.put("cols", cols);
		return maps;
	}

	/**
	 * 保存条件
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception  
	 */
	@RequestMapping("/saveQualification")
	@ResponseBody
	public Map<String,Object> saveQualification(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> operCharacterList = sysLookupLoaderI.getLookUpListByType("CBB_OPER_CHARACTER");
		Collection<SysLookupSimpleVo> logicOperList = sysLookupLoaderI.getLookUpListByType("CBB_LOGIC_OPER");
		Map<String,Object> maps = new HashMap<>();
		String orgId = ThreadContextHelper.getOrgId();
		String deptId = ThreadContextHelper.getDeptId();
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		String targetId = request.getParameter("targetId"); // 用户ID
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String nodeIds = request.getParameter("nodeIds"); // 父页面所选节点ID串
		String[] nodeId = nodeIds.split(",");
		String nodeNames = request.getParameter("nodeNames"); // 父页面所选节点名称串
		String tableId = request.getParameter("tableId"); // 数据表ID
		String authType = request.getParameter("authType"); // 权限类型
		String tableHtml = request.getParameter("tableHtml"); // 表格行内容，HTML代码
		int maxId = Integer.parseInt(request.getParameter("maxId")); // 新增条件table行最大ID，用来循环取值
		String formJson = request.getParameter("formJson");
		String ysf = request.getParameter("ysf");
		String ljgx = request.getParameter("ljgx");

		List<Map<String, Object>> qualificationDetailList = new ArrayList<Map<String, Object>>(); // 条件明细集合

		// 用于将sql语句转换成中文描述
		// 当前所选数据表列
		Map<String, Object> colMap = new HashMap<String, Object>();
		List<Map<String, Object>> colList = this.commTableManagerIntfsService.getCbbTabColumnsByIntfs(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(),
				this.sysId, nodeId[0], tableId);
		for (int i = 0; i < colList.size(); i++) {
			Map<String, Object> map = colList.get(i);
			colMap.put((String) map.get("COL_NAME"), map.get("COL_LABEL"));
		}
		// 运算符
		Map<String, Object> operCharacterMap = new HashMap<String, Object>();
		for (SysLookupSimpleVo simpleVo : operCharacterList) {
			operCharacterMap.put(simpleVo.getLookupCode(), simpleVo.getLookupName());
		}
		// 运算符
		Map<String, Object> logicOperMap = new HashMap<String, Object>();
		for (SysLookupSimpleVo simpleVo : logicOperList) {
			logicOperMap.put(simpleVo.getLookupCode(), simpleVo.getLookupName());
		}

		// 根据所选数据表ID获取数据表明
		List<Map<String, Object>> tableInfoList = this.commTableManagerIntfsService.getCbbTableAndColumnsByTabIdByIntfs(tableId);
		String tableName = (String) tableInfoList.get(0).get("TABLE_TITLE");

		Map<String, Object> qualificationMap = new HashMap<String, Object>();
		if (formJson != null && !"".equals(formJson)) {
			qualificationMap = JsonHelper.getInstance().readValue(formJson, Map.class);
		}
		StringBuffer qualificationSb = new StringBuffer(); // 新增条件生成的sql语句
		StringBuffer qualificationShowSb = new StringBuffer(); // 新增条件生成的sql中文描述
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<LantopUserAuthCondition> luacs = new ArrayList<LantopUserAuthCondition>();
		for (int i = 1; i <= maxId; i++) {
			// 删除列后行ID不会重新排序，所有会出现1,3,4缺少2这样的ID排列，这里根绝有没有当前行的左括号来判断i行是否存在
			if (null != qualificationMap.get("zkh" + i)) {
				LantopUserAuthCondition luac = new LantopUserAuthCondition();
				if (null != qualificationMap.get("startDate") && !"".equals(qualificationMap.get("startDate"))) {
					Date startDate = sdf.parse(qualificationMap.get("startDate")+"");
					luac.setStartDate(startDate);
				}
				if (null != qualificationMap.get("endDate") && !"".equals(qualificationMap.get("endDate"))) {
					Date endDate = sdf.parse(qualificationMap.get("endDate")+"");
					luac.setStartDate(endDate);
				}
				luac.setZkh(qualificationMap.get("zkh" + i)+"");
				luac.setZdm(qualificationMap.get("zd" + i)+"");
				luac.setYsf(qualificationMap.get("ysf" + i)+"");
				luac.setZhi(qualificationMap.get("val" + i)+"");
				luac.setYkh(qualificationMap.get("ykh" + i)+"");
				luac.setGxf(qualificationMap.get("ljgx" + i)+"");
				luac.setOrderBy(BigDecimal.valueOf(i));
				luac.setOrgId(orgId);
				luac.setDeptId(deptId);
				luac.setSysId(this.sysId);
				luacs.add(luac);
				Map<String, Object> qualificationDetailMap = new HashMap<String, Object>();
				qualificationDetailMap.put("ZDM", qualificationMap.get("zd" + i)); // 字段

				StringBuffer qualificationValueSb = new StringBuffer();

				qualificationSb.append(" ");
				qualificationSb.append(qualificationMap.get("zkh" + i)); // 左括号
				qualificationSb.append(" ");
				qualificationSb.append(qualificationMap.get("zd" + i)); // 列名
				qualificationSb.append(" ");

				qualificationValueSb.append(" ");
				qualificationValueSb.append(qualificationMap.get("zkh" + i)); // 左括号
				qualificationValueSb.append(" ");
				qualificationValueSb.append(qualificationMap.get("zd" + i)); // 列名
				qualificationValueSb.append(" ");
				qualificationDetailMap.put("zdVal", qualificationMap.get("zd" + i));

				qualificationDetailMap.put("val", qualificationMap.get("val" + i)); // 值
				qualificationDetailMap.put("ysfVal", qualificationMap.get("ysf" + i)); // 所选运算符
				// 运算符:将运算符英文标识转成对应的符号
				if (qualificationMap.get("ysf" + i).equals("DY")) {
					qualificationSb.append("= '");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值
					qualificationSb.append("'");

					qualificationValueSb.append("= '");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
					qualificationValueSb.append("'");
				} else if (qualificationMap.get("ysf" + i).equals("BDY")) {
					qualificationSb.append("!= '");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值
					qualificationSb.append("'");

					qualificationValueSb.append("!= '");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
					qualificationValueSb.append("'");
				} else if (qualificationMap.get("ysf" + i).equals("BH")) {
					qualificationSb.append("LIKE '%");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值
					qualificationSb.append("%'");

					qualificationValueSb.append("LIKE '%");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
					qualificationValueSb.append("%'");
				} else if (qualificationMap.get("ysf" + i).equals("BBH")) {
					qualificationSb.append("NOT LIKE '%");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值
					qualificationSb.append("%'");

					qualificationValueSb.append("NOT LIKE '%");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
					qualificationValueSb.append("%'");
				} else if (qualificationMap.get("ysf" + i).equals("ZBH")) {
					qualificationSb.append("LIKE '");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值
					qualificationSb.append("%'");

					qualificationValueSb.append("LIKE '");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
					qualificationValueSb.append("%'");
				} else if (qualificationMap.get("ysf" + i).equals("YBH")) {
					qualificationSb.append("LIKE '%");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值
					qualificationSb.append("'");

					qualificationValueSb.append("LIKE '%");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
					qualificationValueSb.append("'");
				} else if (qualificationMap.get("ysf" + i).equals("DAY")) {
					// 大于
					qualificationSb.append("> ");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值

					qualificationValueSb.append("> ");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
				} else if (qualificationMap.get("ysf" + i).equals("DYDY")) {
					// 大于等于
					qualificationSb.append(">= ");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值

					qualificationValueSb.append(">= ");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
				} else if (qualificationMap.get("ysf" + i).equals("XY")) {
					// 小于
					qualificationSb.append("< ");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值

					qualificationValueSb.append("< ");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
				} else if (qualificationMap.get("ysf" + i).equals("XYDY")) {
					// 小于等于
					qualificationSb.append("<= ");
					qualificationSb.append(qualificationMap.get("val" + i)); // 值

					qualificationValueSb.append("<= ");
					qualificationValueSb.append(qualificationMap.get("val" + i)); // 值
				} else if (qualificationMap.get("ysf" + i).equals("WK")) {
					// 为空
					qualificationSb.append("IS NULL ");

					qualificationValueSb.append("IS NULL ");
				} else if (qualificationMap.get("ysf" + i).equals("BWK")) {
					// 不为空
					qualificationSb.append("IS NOT NULL ");

					qualificationValueSb.append("IS NOT NULL ");
				}

				qualificationSb.append(" ");
				qualificationSb.append(qualificationMap.get("ykh" + i)); // 右括号
				qualificationSb.append(" ");

				qualificationValueSb.append(" ");
				qualificationValueSb.append(qualificationMap.get("ykh" + i)); // 右括号
				qualificationValueSb.append(" ");

				qualificationSb.append(qualificationMap.get("ljgx" + i)); // 逻辑关系
				qualificationDetailMap.put("ljgxVal", qualificationMap.get("ljgx" + i));

				qualificationDetailMap.put("QUALIFICATION_VALUE", qualificationValueSb.toString()); // 字段对应的具体条件值
				qualificationDetailMap.put("LOGIC", qualificationMap.get("ljgx" + i)); // 字段对应的具体条件值
				qualificationDetailMap.put("ORDER_BY", i); // 排序字段
				qualificationDetailList.add(qualificationDetailMap);

				// 条件中文描述
				qualificationShowSb.append("(");
				qualificationShowSb.append(colMap.get(qualificationMap.get("zd" + i))); // 字段中文名
				qualificationShowSb.append(operCharacterMap.get(qualificationMap.get("ysf" + i))); // 运算符中文名
				qualificationShowSb.append(qualificationMap.get("val" + i)); // 值
				qualificationShowSb.append(")");
				if (null != qualificationMap.get("ljgx" + i) && !"".equals(qualificationMap.get("ljgx" + i))) {
					qualificationShowSb.append(logicOperMap.get(qualificationMap.get("ljgx" + i))); // 逻辑关系中文名
				}
			}
		}

		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orgId", ThreadContextHelper.getOrgId());
			param.put("deptId", ThreadContextHelper.getDeptId());
			param.put("sysId", this.sysId);
			param.put("targetType", targetType);
			param.put("targetId", targetId);
			param.put("authServiceId", authServiceId);
			param.put("nodeIds", nodeIds);
			param.put("nodeNames", nodeNames);
			param.put("tableId", tableId);
			param.put("tableName", tableName);
			param.put("authType", authType);
			param.put("tableHtml", tableHtml);
			param.put("qualificationSql", qualificationSb.toString());
			param.put("qualificationShowSql", qualificationShowSb.toString());
			param.put("startDate", qualificationMap.get("startDate")); // 开始时间
			param.put("endDate", qualificationMap.get("endDate")); // 结束时间

			this.userAuthService.saveQualification(param); // 保存新增条件
			String cbbAuthResourceId = (String) param.get("cbbAuthResourceId");
			Map<String, Object> parameter = new HashMap<String, Object>();
			parameter.put("resourceId", cbbAuthResourceId);
			parameter.put("nodeIds", nodeIds);
			parameter.put("tableId", tableId);
			parameter.put("actionType", authType);
			userAuthService.insertLantopUserAuthConditions(luacs, parameter);
			Map<String, String> param2 = new HashMap<String, String>();
			param2.put("sysId", this.sysId);
			param2.put("orgId", ThreadContextHelper.getOrgId());
			param2.put("deptId", ThreadContextHelper.getDeptId());
			param2.put("cbbAuthResourceId", cbbAuthResourceId);
			param2.put("cols", "@#@"); // 列信息用特殊字符代替，用于复制条件时替换成目标表的列
			param2.put("ysf", ysf);
			param2.put("ljgx", ljgx);
			this.userAuthService.saveLantopQualificationDetail(qualificationDetailList, param2);
			Map<String,String> nodesMap = new HashMap<String,String>();
			if("A1".equals(authType)){ 
				nodesMap.put("tmNodes", nodeIds);
			}
			if("A2".equals(authType)){  
				nodesMap.put("qwNodes", nodeIds);
			}
			if("A1".equals(authType) || "A2".equals(authType)){
				nodesMap.put("flag", "2");
			}
			maps.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			maps.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}
		return maps;
	}

	/**
	 * 跳转编辑条件页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toEditQualificationJsp")
	public ModelAndView toEditQualificationJsp(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> authTypeList = sysLookupLoaderI.getLookUpListByType("LANTOP_AUTH_TYPE");
		Collection<SysLookupSimpleVo> operCharacterList = sysLookupLoaderI.getLookUpListByType("CBB_OPER_CHARACTER");
		Collection<SysLookupSimpleVo> logicOperList = sysLookupLoaderI.getLookUpListByType("CBB_LOGIC_OPER");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/EditQualification");

		String dialogId = request.getParameter("dialogId");
		String nodeId = request.getParameter("nodeId");
		// 所选树节点名称串
		String nodeName = URLDecoder.decode(request.getParameter("nodeName"), "utf-8");
		nodeName = URLDecoder.decode(nodeName, "utf-8");
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String targetId = request.getParameter("targetId"); // 用户ID
		String authServiceId = request.getParameter("authServiceId"); // 服务ID

		// 数据表
		List<Map<String, Object>> tableList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(),
				this.sysId, nodeId, "");
		// 获取数据表下拉框
		StringBuffer sbtable = new StringBuffer();
		sbtable.append("[");
		Iterator<Map<String, Object>> tableIt = tableList.iterator();
		int index = 0;
		while (tableIt.hasNext()) {
			Map<String, Object> map = tableIt.next();
			String id = (String) map.get("ID");
			String text = (String) map.get("TABLE_TITLE");
			sbtable.append("{id:'" + id + "',");
			sbtable.append("text:'" + text + "'");
			if (index == 0) {
				sbtable.append(",selected:true");
			}
			sbtable.append("},");
			index++;
		}
		String table = sbtable.subSequence(0, sbtable.length() - 1).toString();
		table = table + "]";

		// 权限类型
		StringBuffer sbAuthType = new StringBuffer();
		sbAuthType.append("[");
		Iterator<SysLookupSimpleVo> authTypeIt = authTypeList.iterator();
		index = 0;
		while (authTypeIt.hasNext()) {
			SysLookupSimpleVo simpleVo = authTypeIt.next();
			String id = simpleVo.getLookupCode();
			String text = simpleVo.getLookupName();
			if(id.equals("A3")){
				index++;
				continue;
			}
			sbAuthType.append("{id:'" + id + "',");
			sbAuthType.append("text:'" + text + "'");
			if (index == 0) {
				sbAuthType.append(",selected:true");
			}
			sbAuthType.append("},");
			index++;
		}
		String authType = sbAuthType.subSequence(0, sbAuthType.length() - 1).toString();
		authType = authType + "]";

		// 获取运算符下拉框数据
		StringBuffer sbysf = new StringBuffer();
		sbysf.append("[");
		Iterator<SysLookupSimpleVo> itysf = operCharacterList.iterator();
		while (itysf.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) itysf.next();
			String id = sysLookupSimpleVo.getLookupCode();
			String text = sysLookupSimpleVo.getLookupName();
			sbysf.append("{id:'" + id + "',");
			sbysf.append("text:'" + text + "'");
			sbysf.append("},");
		}
		String ysf = sbysf.subSequence(0, sbysf.length() - 1).toString();
		ysf = ysf + "]";

		// 获取并且/或者下拉框数据
		StringBuffer sbljgx = new StringBuffer();
		sbljgx.append("[");
		Iterator<SysLookupSimpleVo> ithzbq = logicOperList.iterator();
		while (ithzbq.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) ithzbq.next();
			String idhzbq = sysLookupSimpleVo.getLookupCode();
			String texthzbq = sysLookupSimpleVo.getLookupName();
			sbljgx.append("{id:'" + idhzbq + "',");
			sbljgx.append("text:'" + texthzbq + "'");
			sbljgx.append("},");
		}
		String hzbq = sbljgx.subSequence(0, sbljgx.length() - 1).toString();
		hzbq = hzbq + "]";

		mav.addObject("dialogId", dialogId);
		mav.addObject("nodeId", nodeId); // 父页面所选节点
		mav.addObject("table", table); // 数据表
		mav.addObject("authTypeListStr", authType); // 权限类型
		mav.addObject("ysf", ysf); // 运算符
		mav.addObject("ljgx", hzbq); // 逻辑关系
		mav.addObject("nodeName", nodeName);
		mav.addObject("targetType", targetType);
		mav.addObject("targetId", targetId);
		mav.addObject("authServiceId", authServiceId);
		return mav;
	}

	/**
	 * 根据编辑页面所选值获取所要编辑的数据权限配置信息
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/getDataAuthConfig")
	@ResponseBody
	public Map<String,Object> getDataAuthConfig(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String nodeId = request.getParameter("nodeId");
		String targetType = request.getParameter("targetType");
		String targetId = request.getParameter("targetId"); // 用户ID
		String tableId = request.getParameter("tableId");
		String authType = request.getParameter("authType"); // 权限类型
		String authServiceId = request.getParameter("authServiceId"); // 服务ID

		CbbAuthResource cbbAuthResource = this.baseExtendAuthService.getCbbAuthResource(ThreadContextHelper.getOrgId(), this.sysId, targetType, targetId, authServiceId, nodeId
				+ "_" + tableId, authType);
		if (null != cbbAuthResource) {
			LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResource.getId());
			map.put("tableHtml", cbbAuthResource.getDataAuthConfig()); // table下的行记录
			map.put("startDate", ComUtil.Date2String(lantopUserAuthSetExtend.getStartDate())); // 开始时间
			map.put("endDate", ComUtil.Date2String(lantopUserAuthSetExtend.getEndDate())); // 结束时间
		} else {
			map.put("tableHtml", "");
		}
		return map;
	}

	/**
	 * 跳转删除条件页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toDelQualificationJsp")
	public ModelAndView toDelQualificationJsp(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> authTypeList = sysLookupLoaderI.getLookUpListByType("LANTOP_AUTH_TYPE");
		Collection<SysLookupSimpleVo> operCharacterList = sysLookupLoaderI.getLookUpListByType("CBB_OPER_CHARACTER");
		Collection<SysLookupSimpleVo> logicOperList = sysLookupLoaderI.getLookUpListByType("CBB_LOGIC_OPER");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/DelQualification");

		String dialogId = request.getParameter("dialogId");
		String nodeId = request.getParameter("nodeId");
		// 所选树节点名称串
		String nodeName = URLDecoder.decode(request.getParameter("nodeName"), "utf-8");
		nodeName = URLDecoder.decode(nodeName, "utf-8");
		String targetId = request.getParameter("targetId"); // 用户ID
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String authServiceId = request.getParameter("authServiceId"); // 服务ID

		// 数据表
		List<Map<String, Object>> tableList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(),
				this.sysId, nodeId, "");
		// 获取数据表下拉框
		StringBuffer sbtable = new StringBuffer();
		sbtable.append("[");
		Iterator<Map<String, Object>> tableIt = tableList.iterator();
		int index = 0;
		while (tableIt.hasNext()) {
			Map<String, Object> map = tableIt.next();
			String id = (String) map.get("ID");
			String text = (String) map.get("TABLE_TITLE");
			sbtable.append("{id:'" + id + "',");
			sbtable.append("text:'" + text + "'");
			if (index == 0) {
				sbtable.append(",selected:true");
			}
			sbtable.append("},");
			index++;
		}
		String table = sbtable.subSequence(0, sbtable.length() - 1).toString();
		table = table + "]";

		// 权限类型
		StringBuffer sbAuthType = new StringBuffer();
		sbAuthType.append("[");
		Iterator<SysLookupSimpleVo> authTypeIt = authTypeList.iterator();
		index = 0;
		while (authTypeIt.hasNext()) {
			SysLookupSimpleVo simpleVo = authTypeIt.next();
			String id = simpleVo.getLookupCode();
			String text = simpleVo.getLookupName();
			if(id.equals("A3")){
				index++;
				continue;
			}
			sbAuthType.append("{id:'" + id + "',");
			sbAuthType.append("text:'" + text + "'");
			if (index == 0) {
				sbAuthType.append(",selected:true");
			}
			sbAuthType.append("},");
			index++;
		}
		String authType = sbAuthType.subSequence(0, sbAuthType.length() - 1).toString();
		authType = authType + "]";

		// 获取运算符下拉框数据
		StringBuffer sbysf = new StringBuffer();
		sbysf.append("[");
		Iterator<SysLookupSimpleVo> itysf = operCharacterList.iterator();
		while (itysf.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) itysf.next();
			String id = sysLookupSimpleVo.getLookupCode();
			String text = sysLookupSimpleVo.getLookupName();
			sbysf.append("{id:'" + id + "',");
			sbysf.append("text:'" + text + "'");
			sbysf.append("},");
		}
		String ysf = sbysf.subSequence(0, sbysf.length() - 1).toString();
		ysf = ysf + "]";

		// 获取并且/或者下拉框数据
		StringBuffer sbljgx = new StringBuffer();
		sbljgx.append("[");
		Iterator<SysLookupSimpleVo> ithzbq = logicOperList.iterator();
		while (ithzbq.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) ithzbq.next();
			String idhzbq = sysLookupSimpleVo.getLookupCode();
			String texthzbq = sysLookupSimpleVo.getLookupName();
			sbljgx.append("{id:'" + idhzbq + "',");
			sbljgx.append("text:'" + texthzbq + "'");
			sbljgx.append("},");
		}
		String hzbq = sbljgx.subSequence(0, sbljgx.length() - 1).toString();
		hzbq = hzbq + "]";

		mav.addObject("dialogId", dialogId);
		mav.addObject("nodeId", nodeId); // 父页面所选节点
		mav.addObject("table", table); // 数据表
		mav.addObject("authTypeListStr", authType); // 权限类型
		mav.addObject("ysf", ysf); // 运算符
		mav.addObject("ljgx", hzbq); // 逻辑关系
		mav.addObject("nodeName", nodeName);
		mav.addObject("targetId", targetId);
		mav.addObject("targetType", targetType);
		mav.addObject("authServiceId", authServiceId);
		return mav;
	}

	/**
	 * 删除条件
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/delQualification")
	@ResponseBody
	public Map<String,Object> delQualification(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String targetId = request.getParameter("targetId");
		String authServiceId = request.getParameter("authServiceId");
		String nodeId = request.getParameter("nodeId");
		String tableId = request.getParameter("tableId");
		String authType = request.getParameter("authType");
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户

		try {
			// 获取权限资源信息对象，用户获取用户权限设置信息扩展对象
			CbbAuthResource oldCbbAuthResource = this.baseExtendAuthService.getCbbAuthResource(ThreadContextHelper.getOrgId(), sysId, targetType, targetId, authServiceId, nodeId
					+ "_" + tableId, authType);
			this.userAuthService.delLantopQualificationDetail(oldCbbAuthResource.getId()); // 删除条件权限明细信息
			// 删除数据表+权限资源类型所对应的条件信息
			this.baseExtendAuthService.deleteCbbAuthResource(ThreadContextHelper.getOrgId(), sysId, targetType, targetId, authServiceId, nodeId + "_" + tableId, authType);
			// 通过权限资源信息表ID获取用户权限设置信息扩展对象
			LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(oldCbbAuthResource.getId());
			// 删除用户权限设置信息扩展对象
			this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
			
			Map<String,String> nodesMap = new HashMap<String,String>();
			if("A1".equals(authType)){	
				nodesMap.put("tmNodes", nodeId);
			}else if("A2".equals(authType)){	
				nodesMap.put("qwNodes", nodeId);
			}
			if("A1".equals(authType)||"A2".equals(authType)){
				nodesMap.put("flag", "2");
			}

			map.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 加载操作分类
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 */
	@RequestMapping("/getOperateClass")
	public ModelAndView getOperateClass(HttpServletRequest request) {
		
		ModelAndView mav = new ModelAndView();
		mav.setView(null);

		String sysId = request.getParameter("sysId");//系统ID
		if(null == sysId || "".equals(sysId)){
			sysId = "LANTOP";
		}
		String deptId = ThreadContextHelper.getDeptId();
		String orgId = ThreadContextHelper.getOrgId();
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		this.userAuthService.getOperateClass(sysId,deptId,orgId,page, null);

		mav.addObject("rows", page.getEntities());
		mav.addObject("total", page.getEntityCount());
		return mav;
	}

	/**
	 * 保存操作权限分类
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/saveOperateClass")
	public ModelAndView saveOperateClass(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setView(null);
		String id = request.getParameter("id");
		String operateClassName = request.getParameter("operateClassName");

		try {
			LantopOperateClass lantopOperateClass = new LantopOperateClass();
			if (null == id || "".equals(id)) {
				// 添加
				lantopOperateClass.setOrgId(ThreadContextHelper.getOrgId());
				lantopOperateClass.setDeptId(ThreadContextHelper.getDeptId());
				lantopOperateClass.setSysId(this.sysId);
				lantopOperateClass.setOperateClassName(operateClassName);
				this.userAuthService.insertLantopOperateClass(lantopOperateClass);
				mav.addObject("operateClassId", lantopOperateClass.getId());
			} else {
				// 编辑
				lantopOperateClass.setId(id);
				lantopOperateClass.setOperateClassName(operateClassName);
				this.userAuthService.updateLantopOperateClass(lantopOperateClass);
			}
			mav.addObject("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			mav.addObject("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}
		return mav;
	}

	/**
	 * 删除操作权限分类
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/delOperateClass")
	public ModelAndView delOperateClass(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setView(null);

		String ids = "'" + request.getParameter("ids") + "'";
		ids = ids.replace(",", "','");
		try {
			this.userAuthService.delLantopOperateClass(ids);
			mav.addObject("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			mav.addObject("flag", OpResult.failure.ordinal());
		}

		return mav;
	}

	/**
	 * 保存操作权限权限设置
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/saveOperateClassAuthSet")
	public ModelAndView saveOperateClassAuthSet(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setView(null);

		String operateClassId = request.getParameter("operateClassId");
		// String funcMenuId = request.getParameter("funcMenuId");
		// String operateCode = request.getParameter("operateCode");
		String datas = request.getParameter("datas");
		Map<String, Object>[] nodeDatas = JsonUtils.newInstance().Json2Bean2DataGrid(datas, HashMap[].class);

		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orgId", ThreadContextHelper.getOrgId());
			param.put("deptId", ThreadContextHelper.getDeptId());
			param.put("sysId", this.sysId);
			param.put("operateClassId", operateClassId);
			param.put("nodeDatas", nodeDatas);
			this.userAuthService.saveOperateClassAuthSet(param);
			mav.addObject("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			mav.addObject("flag", OpResult.success.ordinal());
			e.printStackTrace();
		}
		return mav;
	}

	/**
	 * 跳转操作权限设置页面
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/toOpeateAuthSetJsp")
	public ModelAndView toOpeateAuthSetJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/OperateAuthSet");

		String dialogId = request.getParameter("dialogId");
		String relTargetId = request.getParameter("relTargetId"); // 已经关联的操作权限分类ID串
		String relTargetNames = URLDecoder.decode(request.getParameter("relTargetNames"), "UTF-8");
		// new String(request.getParameter("relTargetNames").getBytes("iso-8859-1"),"utf-8"); //已关联的操作权限分类名称串
		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
//		String resName = new String(request.getParameter("resName").getBytes("ISO-8859-1"), "UTF-8"); // 模块树名称
		String resName = URLDecoder.decode(request.getParameter("resName"), "UTF-8");

		String actionType = request.getParameter("actionType"); // 操作类型
		String operateAuth = request.getParameter("operateAuth"); // 操作权限

		// 操作权限分类下拉框
		List<Map<String, Object>> operateClassList = this.userAuthService.getLantopOperateClassList(relTargetId);
		StringBuffer operateClassSb = new StringBuffer();
		operateClassSb.append("[");
		for (int i = 0; i < operateClassList.size(); i++) {
			Map<String, Object> map = operateClassList.get(i);
			String id = (String) map.get("ID");
			String name = (String) map.get("OPERATE_CLASS_NAME");
			operateClassSb.append("{id:'" + id + "',");
			operateClassSb.append("text:'" + name + "'");
			operateClassSb.append("},");
		}
		String operateClassListStr = operateClassSb.subSequence(0, operateClassSb.length() - 1).toString();
		operateClassListStr = null == operateClassListStr || "".equals(operateClassListStr) ? "[]" : operateClassListStr + "]";

		mav.addObject("dialogId", dialogId);
		mav.addObject("relTargetId", relTargetId);
		mav.addObject("relTargetNames", relTargetNames);
		mav.addObject("cbbAuthResourceId", cbbAuthResourceId);
		mav.addObject("targetType", targetType);
		mav.addObject("targetId", targetId);
		mav.addObject("authServiceId", authServiceId);
		mav.addObject("resCode", resCode);
		mav.addObject("resName", resName);
		mav.addObject("actionType", actionType);
		mav.addObject("relTargetId", relTargetId);
		mav.addObject("operateAuth", operateAuth);
		mav.addObject("operateClassListStr", operateClassListStr);
		return mav;
	}

	/**
	 * 加载已设置的操作角色
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 */
	@RequestMapping("/getSetOperatreClass")
	@ResponseBody
	public Map<String,Object> getSetOperatreClass(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();

		String relTargetId = request.getParameter("relTargetId");

		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		this.userAuthService.getSetOperatreClass(page, relTargetId);

		map.put("rows", page.getEntities());
		map.put("total", page.getEntityCount());
		return map;
	}

	/**
	 * 保存操作权限设置
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/saveOperateAuthSet")
	@ResponseBody
	public Map<String,Object> saveOperateAuthSet(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		// String targetIds = request.getParameter("targetIds"); //已选操作权限ID串
		String relTargetIds = request.getParameter("relTargetIds"); // 已选操作权限ID串
		String relTargetNames = request.getParameter("relTargetNames"); // 已选操作权限ID串
		// String targetNames = request.getParameter("targetNames"); //已选操作权限名称串
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
		String resName = request.getParameter("resName"); // 模块树名称
		String actionType = request.getParameter("actionType"); // 操作类型
		String operateAuth = request.getParameter("operateAuth"); // 操作权限
		String relTargetType = "1";

		// 根据权限ID串获取权限名称串
		// StringBuffer targetNames = new StringBuffer(); //已选操作权限名称串
		// List<Map<String, Object>> operateClassList = this.userAuthService.getLantopOperateClassList(null); //所有操作权限分类
		// Map<String, Object> operateClassMap = new HashMap<String, Object>();
		// for (int i = 0; i < operateClassList.size(); i++) {
		// Map<String, Object> map = operateClassList.get(i);
		// operateClassMap.put((String)map.get("ID"), map.get("OPERATE_CLASS_NAME"));
		// }
		// String[] ids = targetIds.split(",");
		// for (int i = 0; i < ids.length; i++) {
		// targetNames.append(operateClassMap.get(ids[i]));
		// targetNames.append(",");
		// }
		//
		//
		// StringBuffer relTargetId = new StringBuffer();
		// StringBuffer relTargetName = new StringBuffer();

		try {
			// 获取已经设置的角色信息
			LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResourceId);
			if (null != lantopUserAuthSetExtend) {
				// // relTargetId.append(lantopUserAuthSetExtend.getRelTargetId());
				// // relTargetId.append(",");
				// // relTargetId.append(targetIds.substring(0, targetIds.length()-1));
				// // relTargetName.append(lantopUserAuthSetExtend.getRelTargetName());
				// // relTargetName.append(",");
				// // relTargetName.append(targetNames.substring(0, targetNames.length()-1));

				// 删除原始数据
				this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
			}

			// 新增记录
			LantopUserAuthSetExtend newLantopUserAuthSetExtend = new LantopUserAuthSetExtend();
			newLantopUserAuthSetExtend.setOrgId(ThreadContextHelper.getOrgId());
			newLantopUserAuthSetExtend.setDeptId(ThreadContextHelper.getDeptId());
			newLantopUserAuthSetExtend.setSysId(this.sysId);
			newLantopUserAuthSetExtend.setCbbAuthResourceId(cbbAuthResourceId);
			newLantopUserAuthSetExtend.setTargetType(targetType);
			newLantopUserAuthSetExtend.setTargetId(targetId);
			newLantopUserAuthSetExtend.setAuthServiceId(authServiceId);
			newLantopUserAuthSetExtend.setResCode(resCode);
			newLantopUserAuthSetExtend.setResName(resName);
			newLantopUserAuthSetExtend.setActionType(actionType);
			newLantopUserAuthSetExtend.setOperateAuth(operateAuth);
			newLantopUserAuthSetExtend.setRelTargetType(relTargetType);
			newLantopUserAuthSetExtend.setRelTargetId(relTargetIds);
			newLantopUserAuthSetExtend.setRelTargetName(relTargetNames);
			this.userAuthService.insertLantopUserAuthSetExtend(newLantopUserAuthSetExtend);
			
			// // mav.addObject("relTargetIds", newLantopUserAuthSetExtend.getRelTargetId());
			// // mav.addObject("relTargetNames", newLantopUserAuthSetExtend.getRelTargetName());
			map.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}

		return map;
	}

	/**
	 * 删除操作权限设置
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/delOperateAuthSet")
	@ResponseBody
	public Map<String,Object> delOperateAuthSet(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源ID
		String allTargetIds = request.getParameter("allTargetIds"); // 所有权限分类
		String delTargetIds = request.getParameter("delTargetIds"); // 要删除的权限分类ID串
		delTargetIds = delTargetIds.substring(0, delTargetIds.length() - 1); // 去掉末尾逗号
		String delTargetNames = request.getParameter("delTargetNames"); // 要删除的权限名称串
		delTargetNames = delTargetNames.substring(0, delTargetNames.length() - 1); // 去掉末尾逗号

		try {
			LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResourceId);
			if (null != lantopUserAuthSetExtend) {
				int targetIdIndex = allTargetIds.indexOf(",");
				if (targetIdIndex < 0) {
					// targetIdIndex小于0,只有一个权限，直接删除记录
					this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
				} else {
					// targetIdIndex大于0
					if (allTargetIds.equals(delTargetIds)) {
						// 要删除的权限ID串等于所有权限ID串，删除记录
						this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
					} else {
						// 更新记录REL_TARGET_ID、REL_TARGET_NAME字段
						this.userAuthService.delRoleSet(lantopUserAuthSetExtend, delTargetIds, delTargetNames);
					}
				}
			}

			map.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}

		return map;
	}

	/**
	 * 跳转批量操作权限设置页面
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/toBatchOperateAuthSetJsp")
	public ModelAndView toBatchOperateAuthSetJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/BatchOperateAuthSet");

		String dialogId = request.getParameter("dialogId");
		String relTargetId = request.getParameter("relTargetId"); // 已经关联的操作权限分类ID串
		String relTargetNames = request.getParameter("relTargetNames"); // 已关联的操作权限分类名称串
		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
		String resName =  URLDecoder.decode(request.getParameter("resName"), "utf-8"); // 模块树名称  (进行转码  wangzp add)
		String actionType = request.getParameter("actionType"); // 操作类型
		String operateAuth = request.getParameter("operateAuth"); // 操作权限
		String sysId = request.getParameter("sysId"); // 系统Id

		// 操作权限分类下拉框
		List<Map<String, Object>> operateClassList = this.userAuthService.getLantopOperateClassList(relTargetId);
		StringBuffer operateClassSb = new StringBuffer();
		operateClassSb.append("[");
		for (int i = 0; i < operateClassList.size(); i++) {
			Map<String, Object> map = operateClassList.get(i);
			String id = (String) map.get("ID");
			String name = (String) map.get("OPERATE_CLASS_NAME");
			operateClassSb.append("{id:'" + id + "',");
			operateClassSb.append("text:'" + name + "'");
			operateClassSb.append("},");
		}
		String operateClassListStr = operateClassSb.subSequence(0, operateClassSb.length() - 1).toString();
		operateClassListStr = null == operateClassListStr || "".equals(operateClassListStr) ? "[]" : operateClassListStr + "]";

		mav.addObject("dialogId", dialogId);
		mav.addObject("relTargetId", relTargetId);
		mav.addObject("relTargetNames", relTargetNames);
		mav.addObject("cbbAuthResourceId", cbbAuthResourceId);
		mav.addObject("targetType", targetType);
		mav.addObject("targetId", targetId);
		mav.addObject("authServiceId", authServiceId);
		mav.addObject("resCode", resCode);
		mav.addObject("resName", resName);
		mav.addObject("actionType", actionType);
		mav.addObject("relTargetId", relTargetId);
		mav.addObject("operateAuth", operateAuth);
		mav.addObject("operateClassListStr", operateClassListStr);
		mav.addObject("sysId", sysId);
		return mav;
	}

	/**
	 * 保存操作权限设置
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/saveBatchOperateAuthSet")
	public ModelAndView saveBatchOperateAuthSet(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(null);

		String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		String[] cbbAuthResourceIds = cbbAuthResourceId.split(",");
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		String targetIds = request.getParameter("targetIds"); // 已选操作权限ID串
		// String targetNames = request.getParameter("targetNames"); //已选操作权限名称串
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
		String[] resCodes = resCode.split(",");
		String resName = request.getParameter("resName"); // 模块树名称
		String[] resNames = resName.split(",");
		String actionType = request.getParameter("actionType"); // 操作类型
		String[] actionTypes = actionType.split(",");
		String operateAuth = request.getParameter("operateAuth"); // 操作权限
		String[] operateAuths = operateAuth.split(",");
		String relTargetType = "1";

		// 根据权限ID串获取权限名称串
		StringBuffer targetNames = new StringBuffer(); // 已选操作权限名称串
		List<Map<String, Object>> operateClassList = this.userAuthService.getLantopOperateClassList(null); // 所有操作权限分类
		Map<String, Object> operateClassMap = new HashMap<String, Object>();
		for (int i = 0; i < operateClassList.size(); i++) {
			Map<String, Object> map = operateClassList.get(i);
			operateClassMap.put((String) map.get("ID"), map.get("OPERATE_CLASS_NAME"));
		}
		String[] ids = targetIds.split(",");
		for (int i = 0; i < ids.length; i++) {
			targetNames.append(operateClassMap.get(ids[i]));
			targetNames.append(",");
		}

		StringBuffer relTargetId = new StringBuffer();
		StringBuffer relTargetName = new StringBuffer();

		
		try {
			// 处理批量保存
			for (int i = 0; i < resCodes.length; i++) {
				// 获取已经设置的角色信息
				LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResourceIds[i]);
				if (null != lantopUserAuthSetExtend) {
					relTargetId.append(lantopUserAuthSetExtend.getRelTargetId());
					relTargetId.append(",");
					relTargetId.append(targetIds.substring(0, targetIds.length() - 1));
					relTargetName.append(lantopUserAuthSetExtend.getRelTargetName());
					relTargetName.append(",");
					relTargetName.append(targetNames.substring(0, targetNames.length() - 1));

					// 删除原始数据
					this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
				} else {
					relTargetId.append(targetIds.substring(0, targetIds.length() - 1));
					relTargetName.append(targetNames.substring(0, targetNames.length() - 1));
				}

				// 新增记录
				LantopUserAuthSetExtend newLantopUserAuthSetExtend = new LantopUserAuthSetExtend();
				newLantopUserAuthSetExtend.setOrgId(ThreadContextHelper.getOrgId());
				newLantopUserAuthSetExtend.setDeptId(ThreadContextHelper.getDeptId());
				newLantopUserAuthSetExtend.setSysId(this.sysId);
				newLantopUserAuthSetExtend.setCbbAuthResourceId(cbbAuthResourceIds[i]);
				newLantopUserAuthSetExtend.setTargetType(targetType);
				newLantopUserAuthSetExtend.setTargetId(targetId);
				newLantopUserAuthSetExtend.setAuthServiceId(authServiceId);
				newLantopUserAuthSetExtend.setResCode(resCodes[i]);
				newLantopUserAuthSetExtend.setResName(resNames[i]);
				newLantopUserAuthSetExtend.setActionType(actionTypes[i]);
				newLantopUserAuthSetExtend.setOperateAuth(operateAuths[i]);
				newLantopUserAuthSetExtend.setRelTargetType(relTargetType);
				newLantopUserAuthSetExtend.setRelTargetId(relTargetId.toString());
				newLantopUserAuthSetExtend.setRelTargetName(relTargetName.toString());
				this.userAuthService.insertLantopUserAuthSetExtend(newLantopUserAuthSetExtend);
				relTargetId = new StringBuffer();
				relTargetName = new StringBuffer();
			}
			mav.addObject("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			mav.addObject("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}

		return mav;
	}
	
	
	/**
	 * 保存操作权限设置
	 * @author zyh 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/saveBatchOperateAuthSet_new")
	@ResponseBody
	public Map<String,Object> saveBatchOperateAuthSet_new(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String orgId = ThreadContextHelper.getOrgId();
		this.setSysId(request);
		//String cbbAuthResourceId = request.getParameter("cbbAuthResourceId"); // 权限资源权限ID
		//String[] cbbAuthResourceIds = cbbAuthResourceId.split(",");
		String targetType = request.getParameter("targetType"); // 所选角色类型
		String targetId = request.getParameter("targetId"); // 所选用户ID
		String targetIds = request.getParameter("targetIds"); // 已选操作权限ID串
		// String targetNames = request.getParameter("targetNames"); //已选操作权限名称串
		String authServiceId = request.getParameter("authServiceId"); // 服务ID
		String resCode = request.getParameter("resCode"); // 模块树ID
		String[] resCodes = resCode.split(",");
		//String resName = request.getParameter("resName"); // 模块树名称
		//String[] resNames = resName.split(",");
		//String actionType = request.getParameter("actionType"); // 操作类型
		//String[] actionTypes = actionType.split(",");
		//String operateAuth = request.getParameter("operateAuth"); // 操作权限
		//String[] operateAuths = operateAuth.split(",");
		String relTargetType = "1";

		// 根据权限ID串获取权限名称串
		StringBuffer targetNames = new StringBuffer(); // 已选操作权限名称串
		List<Map<String, Object>> operateClassList = this.userAuthService.getLantopOperateClassList(null); // 所有操作权限分类
		Map<String, Object> operateClassMap = new HashMap<String, Object>();
		for (int i = 0; i < operateClassList.size(); i++) {
			Map<String, Object> map = operateClassList.get(i);
			operateClassMap.put((String) map.get("ID"), map.get("OPERATE_CLASS_NAME"));
		}
		String[] ids = targetIds.split(",");
		for (int i = 0; i < ids.length; i++) {
			targetNames.append(operateClassMap.get(ids[i]));
			targetNames.append(",");
		}

		StringBuffer relTargetId = new StringBuffer();
		StringBuffer relTargetName = new StringBuffer();
		String idsSql = "";
		for (int i = 0; i < resCodes.length; i++) {
			idsSql += "'" + resCodes[i] + "'";
			if (i != resCodes.length - 1) {
				idsSql += ",";
			}
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orgId", orgId);
		param.put("sysId", sysId);
		param.put("targetId", targetId);
		param.put("targetType", targetType);
		param.put("idsSql", idsSql);
		List<Map<String, Object>> list = this.userAuthService.getCbbAuthResourceDatasByNodeId(param);
		try {
			// 处理批量保存
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				String cbbAuthResourceId_search = (String) map.get("CBB_AUTH_RESOURCE_ID");
				String resCode_search = (String) map.get("RES_CODE");
				String resName_search = (String) map.get("RES_NAME");
				String actionType_search = (String) map.get("ACTION_TYPE");
				String operateAuth_search = (String) map.get("OPERATE_AUTH");
				// 获取已经设置的角色信息
				LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResourceId_search);
				if (null != lantopUserAuthSetExtend) {
//					relTargetId.append(lantopUserAuthSetExtend.getRelTargetId());
//					relTargetId.append(",");
					relTargetId.append(targetIds.substring(0, targetIds.length() - 1));
//					relTargetName.append(lantopUserAuthSetExtend.getRelTargetName());
//					relTargetName.append(",");
					relTargetName.append(targetNames.substring(0, targetNames.length() - 1));

					// 删除原始数据
					this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
				} else {
					relTargetId.append(targetIds.substring(0, targetIds.length() - 1));
					relTargetName.append(targetNames.substring(0, targetNames.length() - 1));
				}
				// 新增记录
				LantopUserAuthSetExtend newLantopUserAuthSetExtend = new LantopUserAuthSetExtend();
				newLantopUserAuthSetExtend.setOrgId(ThreadContextHelper.getOrgId());
				newLantopUserAuthSetExtend.setDeptId(ThreadContextHelper.getDeptId());
				newLantopUserAuthSetExtend.setSysId(this.sysId);
				newLantopUserAuthSetExtend.setCbbAuthResourceId(cbbAuthResourceId_search);
				newLantopUserAuthSetExtend.setTargetType(targetType);
				newLantopUserAuthSetExtend.setTargetId(targetId);
				newLantopUserAuthSetExtend.setAuthServiceId(authServiceId);
				newLantopUserAuthSetExtend.setResCode(resCode_search);
				newLantopUserAuthSetExtend.setResName(resName_search);
				newLantopUserAuthSetExtend.setActionType(actionType_search);
				newLantopUserAuthSetExtend.setOperateAuth(operateAuth_search);
				newLantopUserAuthSetExtend.setRelTargetType(relTargetType);
				newLantopUserAuthSetExtend.setRelTargetId(relTargetId.toString());
				newLantopUserAuthSetExtend.setRelTargetName(relTargetName.toString());
				this.userAuthService.insertLantopUserAuthSetExtend(newLantopUserAuthSetExtend);
				relTargetId = new StringBuffer();
				relTargetName = new StringBuffer();
			}
			map.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}

		return map;
	}

	/**
	 * 加载菜单
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/getFuncMenu")
	@ResponseBody
	public Map<String,Object> getFuncMenu(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String id = request.getParameter("id");
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		try {
			if (StringUtils.isEmpty(id)) {
				id = "-1";
			}
			nodes = this.userAuthService.getMenuTreeNode(id);
			map.put("result", OpResult.success.ordinal());
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", OpResult.failure.ordinal());
			map.put("msg", "后台处理异常, " + e.getMessage());
		}
		map.put("data", nodes);
		return map;
	}

	/**
	 * 是否已存在操作权限设置
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/hasOperateAuthSet")
	@ResponseBody
	public Map<String,Object> hasOperateAuthSet(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();

		String cbbAuthResourceIds = request.getParameter("cbbAuthResourceIds");
		cbbAuthResourceIds = "'" + cbbAuthResourceIds.replace(",", "','") + "'";
		int count = this.userAuthService.getLantopUserAuthSetExtendByResourceId(cbbAuthResourceIds);

		map.put("count", count);
		return map;
	}

	/**
	 * 是否初始化用户
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 */
	@RequestMapping("/isInitUser")
	public ModelAndView isInitUser(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(null);

		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String targetId = request.getParameter("targetId");
		String authServiceId = request.getParameter("authServiceId");

		boolean bool = false;
		if (null != this.sysId && !"".equals(this.sysId)) {
			bool = this.baseExtendAuthService.isInitUser(ThreadContextHelper.getOrgId(), this.sysId, targetType, targetId, authServiceId);
		}

		mav.addObject("isInitUser", bool + "");
		return mav;
	}

	/**
	 * 保存用户数据权限设置(初始化用户权限)
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/saveInitUserSetDataAuth")
	@ResponseBody
	public Map<String,Object> saveInitUserSetDataAuth(HttpServletRequest request) throws Exception {
		Map<String,Object> maps = new HashMap<>();

		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String targetId = request.getParameter("targetId"); // 授权维度ID：用户ID
		String datas = request.getParameter("datas"); // 资源列表
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("orgId", ThreadContextHelper.getOrgId());
		parameter.put("sysId", this.sysId);
		parameter.put("targetId", targetId);
		parameter.put("serviceId", "LANTOP_AUTH_SERVER_USERSET");
		// 用户数据权限配置
		Map<String, Object>[] userSetDatas = JsonUtils.newInstance().Json2Bean2DataGrid(datas, HashMap[].class);
		// 要保存的权限集合
		List<CbbAuthResource> cbbAuthResources = new ArrayList<CbbAuthResource>();
		// 要删除的权限字符串，逗号分隔
		StringBuffer delCbbAuthResourcesIds = new StringBuffer();
		Map<String, Object> map = null;
		// 已经注册的数据权限类型
		Map<String, String> operateInfoMap = archiveServiceUserSetBaseAuthService.getOperateInfo();
		for (int i = 0; i < userSetDatas.length; i++) {
			map = userSetDatas[i];
			// 只操作数据节点
			// if(null != map.get("ARCHIVE_CLASS_NODE_TYPE") && map.get("ARCHIVE_CLASS_NODE_TYPE").toString().equals("2")){
			StringBuffer operateTypeCodes = new StringBuffer(); // 权限类型CODE串
			StringBuffer operateTypeNames = new StringBuffer(); // 权限类型NAME串
			// 遍历已注册的数据权限类型值
			int userAuthColSize = operateInfoMap.keySet().size();
			for (int j = 1; j <= userAuthColSize; j++) {
				String key = "A" + j;// 通用代码以字母A开头
				operateTypeCodes.append(key);
				operateTypeNames.append("1");
				// 最后一次不拼接逗号
				if (j != userAuthColSize) {
					operateTypeCodes.append(","); // 英文逗号
					operateTypeNames.append(","); // 英文逗号
				}
			}
			// 0,0,0,0标识没有选中的记录，只保存有授权的记录
			// if(!operateTypeNames.toString().equals("0,0,0,0")){

			// 根据targetType,targetId,authServiceId,res_code like 'code_%',dataAuth is not null判断是否存在条件信息
			int qualification = this.userAuthService.getLantopUserAuthSetExtendCount(targetType, targetId, "LANTOP_AUTH_SERVER_USERSET", (String) map.get("ID"));
			// 只有存在授权的记录保存或已存在sql条件设置
			if (operateTypeNames.indexOf("1") >= 0 || qualification > 0) {
				String code = (String) map.get("ID"); // 档案分类树节点ID
				String name = (String) map.get("ARCHIVE_CLASS_NODE_NAME"); // 档案分类树节点名称
				String cbbAuthResourceId = (String) map.get("CBB_AUTH_RESOURCE_ID"); // 权限资源信息ID

				CbbAuthResource cbbAuthResource = new CbbAuthResource();
				cbbAuthResource.setId(cbbAuthResourceId);
				cbbAuthResource.setOrgId(ThreadContextHelper.getOrgId()); // 组织ID
				cbbAuthResource.setDeptId(ThreadContextHelper.getDeptId()); // 部门ID
				cbbAuthResource.setSysId(this.sysId); // 系统标识ID
				cbbAuthResource.setTargetType(targetType); // 授权维度类型
				cbbAuthResource.setTargetId(targetId); // 授权维度ID
				cbbAuthResource.setAuthServiceId("LANTOP_AUTH_SERVER_USERSET");
				cbbAuthResource.setCode(code); // 所选菜单ID
				cbbAuthResource.setName(name); // 所选菜单名称
				cbbAuthResource.setActionType(operateTypeCodes.toString()); // 授权类型CODE字符串
				cbbAuthResource.setOperateAuth(operateTypeNames.toString()); // 授权类型NAME字符串
				cbbAuthResources.add(cbbAuthResource);
			} else {
				// 2014年12月15日修改：之前已经存在授权，此次操作所有权限被取消，则要删除CBB_AUTH_RESOURCE表授权记录，同时删除LANTOP_USER_AUTH_SET_EXTEND表操作权限设置信息
				// 之前使用的先删除所有授权信息，在保存此次所有授权信息方法会导致已经设置过操作权限LANTOP_USER_AUTH_SET_EXTEND表的记录操作权限和授权表CBB_AUTH_RESOURCE记录脱离关系，导致所有关系丢失
				// 删除被取消授权或未被授权的记录，同时删除操作权限设置
				String cbbAuthResourceId = (String) map.get("CBB_AUTH_RESOURCE_ID"); // 权限资源信息ID
				if (null != cbbAuthResourceId && !cbbAuthResourceId.equals("")) {
					// 存在授权信息，此次操作取消了所有授权信息
					delCbbAuthResourcesIds.append(cbbAuthResourceId);
					delCbbAuthResourcesIds.append(",");
				}
			}
		}
		// }

		try {
			if (null != delCbbAuthResourcesIds && !"".equals(delCbbAuthResourcesIds.toString())) {
				parameter.put("delCbbAuthResourcesIds", delCbbAuthResourcesIds.substring(0, delCbbAuthResourcesIds.length() - 1).toString()); // 要删除的权限资源信息ID串
			}
			this.userAuthService.saveResourceConfig(cbbAuthResources, parameter);
			//调用更新索引方法
			Map<String,Object> nodesMap = new HashMap<String,Object>();
			nodesMap.put("tmNodes", "");
			nodesMap.put("qwNodes", "");
			nodesMap.put("flag", "1");//创建当前用户全部节点的索引
			nodesMap.put("orgId", ThreadContextHelper.getOrgId());
			nodesMap.put("deptId", ThreadContextHelper.getDeptId());
			nodesMap.put("sysId", sysId);
			solrService.insertSolrInfos(nodesMap);
			//this.updateSolrIndexTools(request, nodesMap);
			maps.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			maps.put("userInit", "false");
			maps.put("flag", OpResult.failure.ordinal());
			e.printStackTrace();
		}
		maps.put("userInit", "true");
		return maps;
	}

	/**
	 * 删除权限
	 * @author 张坚 
	 * @param request
	 * @return ModelAndView
	 * @throws Exception 
	 */
	@RequestMapping("/delAuthSet")
	@ResponseBody
	public Map<String,Object> delAuthSet(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String codes = request.getParameter("codes");
		String targetType = request.getParameter("targetType"); // 授权维度类型:数据权限仅针对用户；修改后群组授权时针对群组，其他维度针对用户
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String targetId = request.getParameter("targetId");
		try {
			this.userAuthService.delAuthSet(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), this.sysId, targetType, targetId, codes);
			Map<String,Object> nodesMap = new HashMap<String,Object>();
			if(!"".equals(codes)){
				nodesMap.put("tmNodes", codes);
				nodesMap.put("qwNodes", codes);
				nodesMap.put("flag", "2");
				nodesMap.put("orgId", ThreadContextHelper.getOrgId());
				nodesMap.put("deptId", ThreadContextHelper.getDeptId());
				nodesMap.put("sysId", sysId);
				solrService.insertSolrInfos(nodesMap);
			  //this.updateSolrIndexTools(request,nodesMap);	 
			}
			map.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("flag", OpResult.failure.ordinal());
			throw e;
		}
		return map;
	}

	/**
	 * 跳转权限复制页面
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("toCopyAuthJsp")
	public ModelAndView toCopyAuthJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/CopyAuth");
		String targetType = request.getParameter("targetType");
		//String targetType = "3"; // 权限复制只针对非群组
		String targetId = request.getParameter("targetId"); // 已选择的用户ID,等同于targetId
		String dialogId = request.getParameter("dialogId");

		mav.addObject("targetType", targetType);
		mav.addObject("targetId", targetId);
		mav.addObject("dialogId", dialogId);
		return mav;
	}

	/**
	 * 获取不包含已选择用户外所有用户
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/getAllUser")
	@ResponseBody
	public Map<String,Object> getAllUser(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String json = request.getParameter("param");
		Map<String, Object> searchMap = new HashMap<String, Object>();
		if (json != null && !"".equals(json)) {
			searchMap = JsonHelper.getInstance().readValue(json, Map.class);
		}
		String targetId = request.getParameter("targetId"); // 已选择的用户ID
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));

		this.userAuthService.getAllUser(page, targetId, searchMap);

		map.put("rows", page.getEntities());
		map.put("total", page.getEntityCount());
		return map;
	}

	/**
	 * 保存复制到目标用户(权限复制)
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/saveCopyToTargetUser")
	@ResponseBody
	public Map<String,Object> saveCopyToTargetUser(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String orgId = ThreadContextHelper.getOrgId();
		String deptId = ThreadContextHelper.getDeptId();
		String targetId = request.getParameter("targetId");
		String targetUserIds = request.getParameter("targetUserIds");
		List<LantopUserAuthExtendData> lantopUserAuthExtendDatas = this.userAuthService.getLantopUserAuthExtendData(orgId, deptId, this.sysId, targetId);
		List<LantopUserAuthSetExtend> lantopUserAuthSetExtends =  this.userAuthService.getLantopUserAuthSetExtend(orgId, deptId, this.sysId, targetId);
		List<CbbAuthResource> cbbAuthResources = this.baseExtendAuthService.getCbbAuthResource(orgId, deptId, this.sysId, targetId);
		try {
			this.userAuthService.saveCopyToTargetUser(orgId, deptId, this.sysId, lantopUserAuthSetExtends, lantopUserAuthExtendDatas, cbbAuthResources, targetUserIds);
			this.userAuthService.saveCbbAuthResourceAndUpdateSetExtendByUserIds(orgId, deptId, targetId, cbbAuthResources, targetUserIds);
			String nodeIds = this.userAuthService.getClassNodeIds(orgId, deptId, this.sysId, targetId);
			Map<String, Object> nodesMap = new HashMap<String, Object>();
			if (!"".equals(nodeIds)) {
				nodesMap.put("tmNodes", nodeIds);
				nodesMap.put("qwNodes", nodeIds);
				nodesMap.put("flag", "2");
				nodesMap.put("orgId", ThreadContextHelper.getOrgId());
				nodesMap.put("deptId", ThreadContextHelper.getDeptId());
				nodesMap.put("sysId", sysId);
				solrService.insertSolrInfos(nodesMap);
				//this.updateSolrIndexTools(request, nodesMap);
			}
			map.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			//回滚复制权限数据
			this.userAuthService.deleteAuthCopyDataByRollBack(orgId, deptId, targetId, targetUserIds);
			map.put("flag", OpResult.failure.ordinal());
			throw e;
		}

		return map;
	}

	/**
	 * 跳转条件复制页面
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/toCopyQualificationJsp")
	public ModelAndView toCopyQualificationJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/CopyQualification");

		String targetType = request.getParameter("targetType");
		/*if (!"1".equals(targetType)) {
			targetType = "3"; // 非群组维度则默认为用户维度
		}*/
		//targetType = "3";
		String targetId = request.getParameter("targetId");
		String copyNodeId = request.getParameter("copyNodeId"); // 复制源节点ID
		String dialogId = request.getParameter("dialogId");

		mav.addObject("targetType", targetType);
		mav.addObject("targetId", targetId);
		mav.addObject("copyNodeId", copyNodeId);
		mav.addObject("dialogId", dialogId);
		return mav;
	}

	/**
	 * 保存(条件复制)
	 * @author 张坚 
	 * @param request
	 * @return
	 * @throws Exception ModelAndView
	 */
	@RequestMapping("/saveCopyToTargetModel")
	@ResponseBody
	public Map<String,Object> saveCopyToTargetModel(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> authTypeList = sysLookupLoaderI.getLookUpListByType("LANTOP_AUTH_TYPE");
		Collection<SysLookupSimpleVo> operCharacterList = sysLookupLoaderI.getLookUpListByType("CBB_OPER_CHARACTER");
		Collection<SysLookupSimpleVo> logicOperList = sysLookupLoaderI.getLookUpListByType("CBB_LOGIC_OPER");
		Map<String,Object> maps = new HashMap<>();

		String targetType = request.getParameter("targetType");
		String targetId = request.getParameter("targetId"); // 用户ID
		String copyNodeId = request.getParameter("copyNodeId"); // 复制节点ID
		String targetNodeIds = request.getParameter("targetNodeIds"); // 目标节点ID串
		String targetNodeNames = request.getParameter("targetNodeNames"); // 目标节点ID串
		String[] targetNodeId = targetNodeIds.split(",");
		String[] targetNodeName = targetNodeNames.split(",");
		String authServiceId = "LANTOP_AUTH_SERVER_USERSET"; // 服务ID

		// 获取运算符下拉框数据
		StringBuffer sbysf = new StringBuffer();
		sbysf.append("[");
		Iterator<SysLookupSimpleVo> itysf = operCharacterList.iterator();
		while (itysf.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) itysf.next();
			String id = sysLookupSimpleVo.getLookupCode();
			String text = sysLookupSimpleVo.getLookupName();
			sbysf.append("{id:'" + id + "',");
			sbysf.append("text:'" + text + "'");
			sbysf.append("},");
		}
		String ysf = sbysf.subSequence(0, sbysf.length() - 1).toString();
		ysf = ysf + "]";

		// 获取并且/或者下拉框数据
		StringBuffer sbljgx = new StringBuffer();
		sbljgx.append("[");
		Iterator<SysLookupSimpleVo> ithzbq = logicOperList.iterator();
		while (ithzbq.hasNext()) {
			SysLookupSimpleVo sysLookupSimpleVo = (SysLookupSimpleVo) ithzbq.next();
			String idhzbq = sysLookupSimpleVo.getLookupCode();
			String texthzbq = sysLookupSimpleVo.getLookupName();
			sbljgx.append("{id:'" + idhzbq + "',");
			sbljgx.append("text:'" + texthzbq + "'");
			sbljgx.append("},");
		}
		String hzbq = sbljgx.subSequence(0, sbljgx.length() - 1).toString();
		hzbq = hzbq + "]";

		// 复制源节点下的表
		List<Map<String, Object>> copyTablesList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(ThreadContextHelper.getOrgId(),
				ThreadContextHelper.getDeptId(), this.sysId, copyNodeId, "");

		try {
			// 多个复制对象
			for (int a = 0; a < targetNodeId.length; a++) {
				// 复制目标节点下的表
				List<Map<String, Object>> targetTablesList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(ThreadContextHelper.getOrgId(),
						ThreadContextHelper.getDeptId(), this.sysId, targetNodeId[a], "");

				// 复制源节点下有多张表
				for (int i = 0; i < copyTablesList.size(); i++) {
					Map<String, Object> tableMap = copyTablesList.get(i);
					String tableId = (String) tableMap.get("ID");
					//String tableName = (String) tableMap.get("TABLE_NAME");
					// 没张表对应的权限类型：条目浏览、全文浏览。。。
					for (SysLookupSimpleVo simpleVo : authTypeList) {
						// 表+权限类型下配置的条件明细
						CbbAuthResource cbbAuthResource = this.baseExtendAuthService.getCbbAuthResource(ThreadContextHelper.getOrgId(), this.sysId, targetType, targetId,
								authServiceId, copyNodeId + "_" + tableId, simpleVo.getLookupCode());
						// 配置了条件权限在执行后续操作
						if (null != cbbAuthResource) {
							// 获取条件明细
							List<LantopQualificationDetail> qualificationDetailList = this.userAuthService.getLantopQualificationDetails(cbbAuthResource.getId());
							List<String> colNameList = new ArrayList<String>();
							Map<String, LantopQualificationDetail> qualificationDetailMap = new HashMap<String, LantopQualificationDetail>();
							for (int j = 0; j < qualificationDetailList.size(); j++) {
								LantopQualificationDetail lantopQualificationDetail = qualificationDetailList.get(j);
								colNameList.add(lantopQualificationDetail.getZdm());
								Map<String, Object> map = new HashMap<String, Object>();
								map.put(lantopQualificationDetail.getZdm(), lantopQualificationDetail);
								qualificationDetailMap.put(lantopQualificationDetail.getZdm(), lantopQualificationDetail);
							}

							// 复制目标对应的表
							Map<String, Object> targetTableMap = targetTablesList.get(i);
							String targetTableId = (String) targetTableMap.get("ID");
							String targetTableName = (String) targetTableMap.get("TABLE_NAME");

							// 复制源表和目标表存在的相同字段集合
							List<Map<String, Object>> eqColNameList = this.commTableManagerIntfsService.getCbbColumnsByTableIdAndColNameListByIntfs(targetTableId, colNameList);
							List<LantopQualificationDetail> eqLantopQualificationDetailList = new ArrayList<LantopQualificationDetail>();

							StringBuffer dataAuthSb = new StringBuffer();
							StringBuffer dataAuthConfigSb = new StringBuffer();
							for (int j = 0; j < eqColNameList.size(); j++) {
								Map<String, Object> map = eqColNameList.get(j);
								LantopQualificationDetail lantopQualificationDetail = qualificationDetailMap.get(map.get("COL_NAME"));
								dataAuthSb.append(lantopQualificationDetail.getQualificationValue()); // 条件值
								dataAuthConfigSb.append(lantopQualificationDetail.getQualificationHtml());
								eqLantopQualificationDetailList.add(lantopQualificationDetail);
							}

							List<Map<String, Object>> colList = this.commTableManagerIntfsService.getCbbTabColumnsByIntfs(ThreadContextHelper.getOrgId(),
									ThreadContextHelper.getDeptId(), this.sysId, targetNodeId[0], targetTableId);
							// 获取数据表下拉框
							StringBuffer sbcol = new StringBuffer();
							sbcol.append("[");
							Iterator<Map<String, Object>> colIt = colList.iterator();
							while (colIt.hasNext()) {
								Map<String, Object> map = colIt.next();
								String id = (String) map.get("COL_NAME");
								String text = (String) map.get("COL_LABEL");
								sbcol.append("{id:'" + id + "',");
								sbcol.append("text:'" + text + "'");
								sbcol.append("},");
							}
							String cols = sbcol.subSequence(0, sbcol.length() - 1).toString();
							cols = null == cols || "".equals(cols) ? "[]" : cols + "]";

							String tableHtml = dataAuthConfigSb.toString().replace("@#@", cols);

							LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResource.getId());

							Map<String, Object> param = new HashMap<String, Object>();
							param.put("orgId", ThreadContextHelper.getOrgId());
							param.put("deptId", ThreadContextHelper.getDeptId());
							param.put("sysId", this.sysId);
							param.put("targetType", targetType);
							param.put("targetId", targetId);
							param.put("authServiceId", authServiceId);
							param.put("nodeIds", targetNodeId[a]);
							param.put("nodeNames", targetNodeName[a]);
							param.put("tableId", targetTableId);
							param.put("tableName", targetTableName);
							param.put("authType", simpleVo.getLookupCode());
							param.put("tableHtml", tableHtml);
							param.put("qualificationSql", dataAuthSb.toString());
							param.put("qualificationShowSql", ""); // 中文描述
							param.put("startDate", lantopUserAuthSetExtend.getStartDate()); // 开始时间
							param.put("endDate", lantopUserAuthSetExtend.getEndDate()); // 结束时间

							this.userAuthService.saveQualification(param); // 保存新增条件
							String cbbAuthResourceId = (String) param.get("cbbAuthResourceId");

							for (int j = 0; j < eqLantopQualificationDetailList.size(); j++) {
								LantopQualificationDetail lantopQualificationDetail = eqLantopQualificationDetailList.get(j);
								lantopQualificationDetail.setCbbAuthResourceId(cbbAuthResourceId);
								// 复制明细并新增
								this.userAuthService.saveLantopQualifcicationDetail(lantopQualificationDetail);
							}
						}
					}
				}
			}
			Map<String,Object> nodesMap = new HashMap<String,Object>();
			if(!"".equals(targetNodeIds)){
				nodesMap.put("tmNodes", targetNodeIds);
				nodesMap.put("qwNodes", targetNodeIds);
				nodesMap.put("flag", "2");
				nodesMap.put("orgId", ThreadContextHelper.getOrgId());
				nodesMap.put("deptId", ThreadContextHelper.getDeptId());
				nodesMap.put("sysId", sysId);
				solrService.insertSolrInfos(nodesMap);
			    //this.updateSolrIndexTools(request,nodesMap);	 
			}
			maps.put("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			maps.put("flag", OpResult.failure.ordinal());
			throw e;
		}
		return maps;
	}
	
	/**
	 * 跳转密级权限控制页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toSecretLevelJsp")
	public ModelAndView toSecretLevelJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("avicit/im/lantop/userauthset/secretLevelManager");
		
		// 获取系统标识ID
		this.sysId = request.getParameter("sysId");
		this.sysId = this.commSysInfoIntfsService.getSysIdByIntfs(this.sysId); // 系统ID
				
		Map<String, Object> param1 = new HashMap<String, Object>();
		param1.put("CONFIG_KEY_CODE", "LANTOP_SM_CODE");
		List<Map<String, Object>> list = this.userAuthService.getSysConfig(param1);
		
		if ( null != list && list.size() > 0 ) {
			mav.addObject("dataMap", list.get(0));
		} else {
			//没有配置记录，初始化配置
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("ID", ComUtil.getId());
			dataMap.put("SYS_ID", this.sysId);
			dataMap.put("DEPT_ID", ThreadContextHelper.getDeptId());
			dataMap.put("ORG_ID", ThreadContextHelper.getOrgId());
			dataMap.put("CONFIG_KEY_NAME", "用户权限密级控制");
			dataMap.put("CONFIG_KEY_CODE", "LANTOP_SM_CODE");
			dataMap.put("CONFIG_KEY_VALUE", "1");
			dataMap.put("CREATION_DATE", ComUtil.Date2String(new Date()));
			dataMap.put("CREATED_BY", SessionHelper.getLoginSysUserId(request));
			dataMap.put("LAST_UPDATE_DATE", ComUtil.Date2String(new Date()));
			dataMap.put("LAST_UPDATED_BY", SessionHelper.getLoginSysUserId(request));
			dataMap.put("LAST_UPDATE_IP", SessionHelper.getClientIp(request));
			//允许对密级范围外的档案利用申请
			dataMap.put("ATTRIBUTE_08", "false");
			this.userAuthService.saveSysConfig(dataMap);
			mav.addObject("dataMap", dataMap);
		}
		return mav;
	}
	
	/**
	 * 保存系统配置
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveSysConfig")
	public ModelAndView saveSysConfig(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setView(null);
		
		String dataId = request.getParameter("dataId");
		String keyValue = request.getParameter("keyValue");
		String secretCheck = request.getParameter("secretCheck");
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("ID", dataId);
			param.put("CONFIG_KEY_VALUE", keyValue);
			//允许对密级范围外的档案利用申请
			param.put("ATTRIBUTE_08", secretCheck);
			this.userAuthService.updateSysConfig(param);
			
			//修改密级权限--更新solr索引--新增更新记录
			Map<String, Object> nodesMap = new HashMap<String, Object>();
			nodesMap.put("tmNodes", "");
			nodesMap.put("qwNodes", "");
			nodesMap.put("orgId", ThreadContextHelper.getOrgId());
			nodesMap.put("deptId", ThreadContextHelper.getDeptId());
			nodesMap.put("sysId", sysId);
			nodesMap.put("flag", "1");
			solrService.insertSolrInfos(nodesMap);
			
			mav.addObject("flag", "0");
		} catch (Exception e) {
			mav.addObject("flag", "1");
			e.printStackTrace();
		}
		return mav;
	}

	/**
	 * 动态更新检索的索引
	 * @date 2016-08-16
	 * @author 王志鹏 update
	 * @param request
	 * @param nodesMap(节点信息)
	 */
	public void updateSolrIndexTools(HttpServletRequest request, Map<String, String> nodesMap) throws Exception {
		String tmNodes = nodesMap.get("tmNodes");
		String qwNodes = nodesMap.get("qwNodes");
		String flag = nodesMap.get("flag"); // 执行标识
		String sysConfig = userAuthIntfsService.getMjSysConfigByIntfs(null); // 2为启用目录密级权限控制,4为目录和全文都控制
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orgId", ThreadContextHelper.getOrgId());
		param.put("sysId", this.sysId);
		param.put("deptId", ThreadContextHelper.getDeptId());
		String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);// 组织应用ID
		param.put("orgIdentity", orgIdentity);
		param.put("tmNodes", tmNodes);
		param.put("qwNodes", qwNodes);
		param.put("flag", flag);
		// 密级控制
		if ("2".equals(sysConfig) || "4".equals(sysConfig)) {
			// 开启目录为 0
			param.put("secretFlag", "0");
		} else {
			// 其他为1
			param.put("secretFlag", "1");
		}
		param.put("userId", SessionHelper.getLoginSysUserId(request));
		param.put("ip", SessionHelper.getClientIp(request));
		
		String searchConfig = JProperties.getFileProperties("searchType");// 通过配置文件，获取当前检索配置
		String tmIde="";
		if (null != searchConfig && "solr".equals(searchConfig.toLowerCase())) {
			//调用过程将授权数据插入临时表，并返回批次号
			//1.条目
			tmIde = userAuthIntfsService.updateSolrIndexTm(param);
			//计算当前批次条目临时表数据量
			int tmTotal = userAuthIntfsService.getTmtotal(tmIde);
			//由于临时表数据量过大，需要分段读取临时表数据，暂定50000条记录读一次
			if(tmTotal <= 50000){
				System.out.println("条目临时数据，当前批次：" + tmIde + "，数据总是为："+ tmTotal +"数据量小于50000");
				//构造创建索引使用的集合
				int start = 1;
				int end = 50000;
				Map<String, Object> mapTm = userAuthIntfsService.getSolrIndexMapTm(tmIde,start,end);
				//调用创建索引接口
				Map<String, Map<String, String>> map1 = new HashMap<String, Map<String, String>>();
				Iterator<String> itData = mapTm.keySet().iterator();
				while (itData.hasNext()) {
					String dataId = String.valueOf(itData.next());// 目录ID或附件ID
					Map<String, String> uMap = (Map<String, String>) mapTm.get(dataId);// 具体用户集合
					map1.put(dataId, uMap);
				}
				Map<String, Object> map2 = new HashMap<String, Object>();
				String path = request.getSession().getServletContext().getRealPath("/");
				if (!path.endsWith(File.separator)) {
					path = path + File.separator;
				}
				map2.put("path", path);
				map2.put("orgId", ThreadContextHelper.getOrgId());
				map2.put("deptId", ThreadContextHelper.getDeptId());
				map2.put("sysId", this.sysId);

				final Map<String, Map<String, String>> map3 = map1;
				final Map<String, Object> map4 = map2;
				Thread t = new Thread() {
					public void run() {
						try {
							cbbSearchengIntfsService.updateSolrIndex(map3, map4);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};
				t.start();
				System.out.println("条目索引更新成功 批次号为：" + tmIde + "---success!");
			}else{
				System.out.println("条目临时数据，当前批次：" + tmIde + "，数据总是为："+ tmTotal +"数据量大于50000");
				int yu = tmTotal/50000;//求商
				for(int q=0;q<yu;q++){
					System.out.println("条目临时数据，当前批次：" + tmIde + "，进入循环，当前循环次数：" + (q + 1));
					//构造创建索引使用的集合
					int start = (q+1)*50000;
					int end = (q+2)*50000;
					Map<String, Object> mapTm = userAuthIntfsService.getSolrIndexMapTm(tmIde,start,end);
					//调用创建索引接口
					Map<String, Map<String, String>> map1 = new HashMap<String, Map<String, String>>();
					Iterator<String> itData = mapTm.keySet().iterator();
					while (itData.hasNext()) {
						String dataId = String.valueOf(itData.next());// 目录ID或附件ID
						Map<String, String> uMap = (Map<String, String>) mapTm.get(dataId);// 具体用户集合
						map1.put(dataId, uMap);
					}
					Map<String, Object> map2 = new HashMap<String, Object>();
					String path = request.getSession().getServletContext().getRealPath("/");
					if (!path.endsWith(File.separator)) {
						path = path + File.separator;
					}
					map2.put("path", path);
					map2.put("orgId", ThreadContextHelper.getOrgId());
					map2.put("deptId", ThreadContextHelper.getDeptId());
					map2.put("sysId", this.sysId);

					final Map<String, Map<String, String>> map3 = map1;
					final Map<String, Object> map4 = map2;
					Thread t = new Thread() {
						public void run() {
							try {
								cbbSearchengIntfsService.updateSolrIndex(map3, map4);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					};
					t.start();
					System.out.println("条目索引更新成功 批次号为：" + tmIde + "---success!，当前循环次数：" + (q + 1));
				}
				System.out.println("条目索引更新成功，当前批次：" + tmIde + "，数据总数为：" + tmTotal + " 数据量大于50000 ---success!");
			}
		}
		//2.全文
		// 密级控制
		if ("3".equals(sysConfig) || "4".equals(sysConfig)) {
			// 开启全文为 0
			param.put("secretFlag", "0");
		} else {
			// 其他为1
			param.put("secretFlag", "1");
		}
		String qwIde = userAuthIntfsService.updateSolrIndexQw(param);
		//计算当前批次全文临时表数据量
		int qwTotal = userAuthIntfsService.getQwtotal(qwIde);
		//由于临时表数据量过大，需要分段读取临时表数据，暂定50000条记录读一次
		if(qwTotal <= 50000){
			System.out.println("全文临时数据，当前批次：" + qwIde + "，数据总数为：" + qwTotal + " 数据量小于50000");
			//构造创建索引使用的集合
			int start = 1;
			int end = 50000;
			Map<String, Object> mapQw = userAuthIntfsService.getSolrIndexMapQw(qwIde,start,end);
			//调用创建索引接口
			Map<String, Map<String, String>> map1 = new HashMap<String, Map<String, String>>();
			Iterator<String> itData = mapQw.keySet().iterator();
			while (itData.hasNext()) {
				String dataId = String.valueOf(itData.next());// 目录ID或附件ID
				Map<String, String> uMap = (Map<String, String>) mapQw.get(dataId);// 具体用户集合
				map1.put(dataId, uMap);
			}
			Map<String, Object> map2 = new HashMap<String, Object>();
			String path = request.getSession().getServletContext().getRealPath("/");
			if (!path.endsWith(File.separator)) {
				path = path + File.separator;
			}
			map2.put("path", path);
			map2.put("orgId", ThreadContextHelper.getOrgId());
			map2.put("deptId", ThreadContextHelper.getDeptId());
			map2.put("sysId", this.sysId);

			final Map<String, Map<String, String>> map3 = map1;
			final Map<String, Object> map4 = map2;
			Thread t = new Thread() {
				public void run() {
					try {
						cbbSearchengIntfsService.updateSolrIndex(map3, map4);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			t.start();
			System.out.println("全文索引更新成功 批次号为：" + qwIde + "---success!");
		}else{
			System.out.println("全文临时数据，当前批次：" + qwIde + "，数据总数为：" + qwTotal + " 数据量大于50000");
			int yu = qwTotal/50000;//求商
			for(int q=0;q<yu;q++){
				System.out.println("全文临时数据，当前批次：" + qwIde + "，进入循环，当前循环次数：" + (q + 1));
				//构造创建索引使用的集合
				int start = (q+1)*50000;
				int end = (q+2)*50000;
				Map<String, Object> mapQw = userAuthIntfsService.getSolrIndexMapQw(qwIde,start,end);
				//调用创建索引接口
				Map<String, Map<String, String>> map1 = new HashMap<String, Map<String, String>>();
				Iterator<String> itData = mapQw.keySet().iterator();
				while (itData.hasNext()) {
					String dataId = String.valueOf(itData.next());// 目录ID或附件ID
					Map<String, String> uMap = (Map<String, String>) mapQw.get(dataId);// 具体用户集合
					map1.put(dataId, uMap);
				}
				Map<String, Object> map2 = new HashMap<String, Object>();
				String path = request.getSession().getServletContext().getRealPath("/");
				if (!path.endsWith(File.separator)) {
					path = path + File.separator;
				}
				map2.put("path", path);
				map2.put("orgId", ThreadContextHelper.getOrgId());
				map2.put("deptId", ThreadContextHelper.getDeptId());
				map2.put("sysId", this.sysId);

				final Map<String, Map<String, String>> map3 = map1;
				final Map<String, Object> map4 = map2;
				Thread t = new Thread() {
					public void run() {
						try {
							cbbSearchengIntfsService.updateSolrIndex(map3, map4);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};
				t.start();
				System.out.println("全文索引更新成功 批次号为：" + qwIde + "---success!，当前循环次数：" + (q + 1));
			}
			System.out.println("全文临时数据，当前批次：" + qwIde + "，数据总数为：" + qwTotal + " 数据量大于50000 ---success!");
		}
		if(!tmIde.equals("")){
			//删除条目及临时表中的数据
			userAuthIntfsService.deleteSolrIndexTm(tmIde, "tm");
			System.out.println("删除条目临时表数据成功 批次号为：" + tmIde + "---success!");
		}
		userAuthIntfsService.deleteSolrIndexTm(qwIde, "qw");
		System.out.println("删除全文临时表数据成功 批次号为：" + qwIde + "---success!");
	}
	
	/**
	 * 加载角色信息
	 */
	@RequestMapping("/getUserRole")
	@ResponseBody
	public Map<String,Object> getUserRole(HttpServletRequest request) throws Exception{
		Map<String,Object> map = new HashMap<>();
		String orgId = ThreadContextHelper.getOrgId();
		String name = request.getParameter("roleQueryKey");//查询条件
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));
		this.userAuthService.getUserRoleList(page, name,orgId);
		map.put("rows", page.getEntities());
		map.put("total", page.getEntityCount());
		return map;
	}
	
	@RequestMapping("/doSetAuth")
	public ModelAndView doSetAuth(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		Map<String, Object> param = new HashMap<String, Object>();
		String targetId = "1"; // 用户id
		param.put("targetType", "3");
		param.put("targetId", targetId);// 用户id
		
		param.put("id", "8a58c62061827309016182da064b0315"); // 需要授权的模版id
		List<Map<String, Object>> list = this.userAuthService.getUserAuthDatasByIdsParam(param);
		String targetType = request.getParameter("targetType");
		try {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				String cbbAuthResourceId = (String) map.get("ID");
				String resCode = (String) map.get("CODE");
				String resName = (String) map.get("NAME");
				String relTargetType = "1";
				String actionType = (String) map.get("ACTION_TYPE");
				String operateAuth = (String) map.get("OPERATE_AUTH");
				String relTargetIds = "8a58bc134a5d00e5014a5d0a4e7f0005"; //操作权限分类  需要传递操作权限分类的id  利用管理员id 
				String relTargetNames = "系统管理员权限"; // 操作权限分类名称  需要填写 操作权限分类的名称   例如   利用管理员权限
				// 获取已经设置的角色信息
				LantopUserAuthSetExtend lantopUserAuthSetExtend = this.userAuthService.getLantopUserAuthSetExtend(cbbAuthResourceId);
				if (null != lantopUserAuthSetExtend) {
					// 删除原始数据
					this.userAuthService.delLantopUserAuthSetExtend(lantopUserAuthSetExtend.getId());
				}

				// 新增记录
				LantopUserAuthSetExtend newLantopUserAuthSetExtend = new LantopUserAuthSetExtend();
				newLantopUserAuthSetExtend.setOrgId(ThreadContextHelper.getOrgId());
				newLantopUserAuthSetExtend.setDeptId(ThreadContextHelper.getDeptId());
				newLantopUserAuthSetExtend.setSysId(this.sysId);
				newLantopUserAuthSetExtend.setCbbAuthResourceId(cbbAuthResourceId);
				newLantopUserAuthSetExtend.setTargetType(targetType);
				newLantopUserAuthSetExtend.setTargetId(targetId);
				newLantopUserAuthSetExtend.setAuthServiceId("LANTOP_AUTH_SERVER_USERSET");
				newLantopUserAuthSetExtend.setResCode(resCode);
				newLantopUserAuthSetExtend.setResName(resName);
				newLantopUserAuthSetExtend.setActionType(actionType);
				newLantopUserAuthSetExtend.setOperateAuth(operateAuth);
				newLantopUserAuthSetExtend.setRelTargetType(relTargetType);
				newLantopUserAuthSetExtend.setRelTargetId(relTargetIds);
				newLantopUserAuthSetExtend.setRelTargetName(relTargetNames);
				this.userAuthService.insertLantopUserAuthSetExtend(newLantopUserAuthSetExtend);
			}
			mav.addObject("flag", OpResult.success.ordinal());
		} catch (Exception e) {
			mav.addObject("flag", OpResult.failure.ordinal());
		}
		return mav;
	}
	
	/**
	 * 加载角色信息
	 */
	@RequestMapping("/getUsers")
	@ResponseBody
	public Map<String,Object> getUsers(HttpServletRequest request, String id, String type) throws Exception{
		Map<String,Object> map = new HashMap<>();
		String orgId = ThreadContextHelper.getOrgId();//组织应用ID
		String userName = request.getParameter("search_USER_NAME");//查询条件
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		page.setPage(ComUtil.getPageSize(pageNo));
		page.setRows(ComUtil.getPageNo(pageSize));
		this.userAuthService.getUsers(page, userName,orgId,id);
		map.put("rows", page.getEntities());
		map.put("total", page.getEntityCount());
		return map;
	}
	
	
}
